Perl: use constant in regex 

Joined:
04/09/2007
Posts:
753

October 27, 2008 04:01:58    Last update: October 27, 2008 22:30:12
#!/usr/bin/perl
@a = ('bar', 'bar2', 'foo', 'foo2');
use constant FOO => 'bar';

# use constant FOO in regex. Using /FOO/ directly matches literal "FOO"
@b = grep { /${\(FOO)}/ } @a;
print join(",", @b), "\n";

# define regex with qr (regex quote) operator
$m = qr/${\(FOO)}/;
@d = grep { m{$m} } @a;
print join(",", @d), "\n";

if ("bar" =~ $m) {
    print "Matches bar\n";
}
elsif ("foo" =~ $m) {
    print "Should not match foo!\n";
}
Share |
| Comment  | Tags