Book HomeLearning Perl, 3rd EditionSearch this book

9.2. 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.

9.2.1. Case-insensitive Matching with /i

To make a case-insensitive pattern match, so that 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 (/\byes\b/i) {  # case-insensitive match
  print "In that case, I recommend that you go bowling.\n";
}

9.2.2. Matching Any Character with /s

Do you ever feel frustrated that the dot (.) won't match newline? 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[194] 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:

[194]If you wish to change just some of them, and not all, you'll probably want to replace just those few with [\d\D].

$_ = "I saw Barney\ndown at the bowling alley\nwith Fred\nlast night.\n";
if (/\bBarney\b.*\bFred\b/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.

9.2.3. Combining Option Modifiers

If you have more than one option modifier to use on the same pattern, they may be used one after the other; their order isn't significant:

if (/\bbarney\b.*\bfred\b/si) {  # both /s and /i
  print "That string mentions Fred after Barney!\n";
}

9.2.4. Other Options

There are many other option modifiers available. We'll cover those as we get to them, or you can read about them in the perlop manpage and in the descriptions of m// and the other regular expression operators that we'll see later in this chapter.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.