Regular Expressions : A Wealth of Possibilities
While unofficially Perl stands for Pathologically Eclectic Rubbish Lister,
the official acronym is Practical Extraction and Reporting Language.
What makes Perl so well suited to extracting and reporting is its implementation
of regular expressions. Regexps, or regex's as they are often called are a
powerful and compact language that can do amazing things when it comes to working
with character strings.
How Hard are Regex's to Work With?
The power of regular expressions lie partly in their compactness. This has a
pitfall in that very small details can make huge differences in the behavior of
your regexp. In the same way that a slight change in pressure on the gas pedal
of a sports car may make a big difference in how the car drives, the addition or
omission of a single character in a regex can make all the difference in the
world between doing what you want -- or not.
Some Examples With Explanations
All the examples that follow are based on the following scalar assignment :
my $str = q|The power of regular expressions lie
partly in their compactness. This has a pitfall in that
very small details can make huge differences in the
behavior of your regexp. In the same way that a slight
change in pressure on the gas pedal of a sports car may
make a big difference in how the car drives, the addition
or omission of a single character in a regex can make all
the difference in the world between doing what you want
-- or not.|
$str =~ /The/;
Succeeds, because 'The' is found in the string.
$str =~ /^power/;
The carrot character, '^' when put at the beginning of a regex indicates
that what follows must be found at the beginning of the string being searched.
Therefore, this fails because 'power' is not found in the beginning of the
string.
$str =~ /^the/;
This fails because regexps are case sensitive by default.
$str =~ /^the/i;
This succeeds, because the character 'i' when put at the end of the regexp
in this way specifies that the matching is to be case insensitive.
$str =~ /lie partly/;
Fails because there is a newline character between 'lie' and 'partly'.
$str =~ /lie partly/s;
Succeeds because placing the 's' at the end of the regexp instructs Perl
to treat the string as a single line, ignoring any newline characters.
|