Previous Page
Next Page

12.10. Named Characters

Prefer named characters to escaped metacharacters.

As an alternative to the previous guideline, Perl 5.6 (and later) supports named characters in regexes. As previously discussed[*], this mechanism is much better for "unprintable" components of a regex. For example, instead of:

[*] "Escaped Characters" in Chapter 4.

    if ($escape_seq =~ /\177 \006 \030 Z/xms) {   # Octal DEL-ACK-CAN-Z
        blink(182);
    }

use:


    use charnames qw( :full );

    if ($escape_seq =~ m/\N{DELETE} \N{ACKNOWLEDGE} \N{CANCEL} Z/xms) {
        blink(182);
    }

Note, however that named whitespace characters are treated like ordinary whitespace (i.e., they're ignored) under the /x flag:

    use charnames qw( :full );

    # and later...

    $name =~ m{ harry \N{SPACE} s \N{SPACE} truman     # harrystruman
              | harry \N{SPACE} j \N{SPACE} potter     # harryjpotter
              }ixms;

You would still need to put them in characters classes to make them match:


    use charnames qw( :full );

    
# and later...
$name =~ m{ harry [\N{SPACE}] s [\N{SPACE}] truman
# harry s truman
| harry [\N{SPACE}] j [\N{SPACE}] potter
# harry j potter
}ixms;

    Previous Page
    Next Page