Perl Best Practices [Electronic resources]

Damian Conway

نسخه متنی -صفحه : 317/ 180
نمايش فراداده

12.9. Metacharacters

Prefer singular character classes to escaped metacharacters .

Escaped metacharacters are harder to decipher, and harder to distinguish from their unescaped originals:

m/ \{ . \. \d{2} \} /xms;

The alternative is to put each metacharacter in its own tiny, one-character character class, like so:

m/ [{] . [.] \d{2} [}] /xms;

Once you're familiar with this convention, it's very much easier to see the literal metacharacters when they're square-bracketed. That's particularly true for spaces under the /x flag. For example, the literal spaces to be matched in:

$name =~ m{ harry [ ] s [ ] truman | harry [ ] j [ ] potter }ixms;

stand out much better than those in:

$name =~ m{ harry \ s \ truman
| harry \ j \ potter
}ixms;

Note, however, that this approach can reduce the optimizer's ability to accelerate pattern matching under some versions of Perl. If benchmarking (see Chapter 19) indicates that this may be a problem for you, try the alternative approach suggested in the next guideline.