Chapter 2. Advanced Regular Expressions
Regular expressions, or just regexes, are at the core of Perl’s text processing, and certainly are one of the features that made Perl so popular. All Perl programmers pass through a stage where they try to program everything as regexes and, when that’s not challenging enough, everything as a single regex. Perl’s regexes have many more features than I can, or want, to present here, so I include those advanced features I find most useful and expect other Perl programmers to know about without referring to perlre, the documentation page for regexes.
References to Regular Expressions
I don’t have to know every pattern at the time that I code something. Perl allows me to interpolate
variables into regexes. I might hard code those values, take them from
user input, or get them in any other way I can get or create data. Here’s
a tiny Perl program to do grep’s job. It takes the
firstF argument from the command line and uses it as the regex in the
while statement. That’s nothing special
(yet); we showed you how to do this in Learning Perl. I can use the string
in $regex as my pattern, and Perl
compiles it when it interpolates the string in the match
operator:[1]
#!/usr/bin/perl
# perl-grep.pl
my $regex = shift @ARGV;
print "Regex is [$regex]\n";
while( <> )
{
print if m/$regex/;
}I can use this program from the command line to search for patterns
in files. Here I search for the pattern new in all of the Perl programs in the current
directory:
% perl-grep.pl ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access