Option Modifiers
There are several option modifier letters, sometimes called flags, which may be appended as a group right after the ending delimiter of a regular expression to change its behavior from the default.
Case-Insensitive Matching with /i
To make a case-insensitive pattern match, so you can match
FRED as easily as fred or Fred, use the /i modifier:
print "Would you like to play a game? ";
chomp($_ = <STDIN>);
if (/yes/i) { # case-insensitive match
print "In that case, I recommend that you go bowling.\n";
}Matching Any Character with /s
By default, the dot (.)
doesn’t match newline, and this makes sense for most “look within a
single line” patterns. If you might have newlines in your strings, and
you want the dot to be able to match them, the /s modifier will do the job. It changes
every dot[*] in the pattern to act like the character class [\d\D] does, which is to match any
character, even if it is a newline. Of course, you have to have a
string with newlines for this to make a difference:
$_ = "I saw Barney\ndown at the bowling alley\nwith Fred\nlast night.\n";
if (/Barney.*Fred/s) {
print "That string mentions Fred after Barney!\n";
}Without the /s modifier, that
match would fail, since the two names aren’t on the same line.
Adding Whitespace with /x
The third modifier you’ll see allows you to add arbitrary whitespace to a pattern to make it easier to read:
/-?\d+\.?\d*/ # what is this doing? / -? \d+ \.? \d* /x # a little better
Since the /x allows whitespace inside the pattern, ...
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