Chapter 23. Search and Replace Functions

[ expr =~ ] [ m ] /pattern/ [ g [ c ] ] [ i ] [ m ] [ o ] [ s ] [ x ]

Searches expr (default $_) for a pattern.

For =~, its negation !~ may be used, which is true when =~ would return false, and vice versa.

After a successful match, the following special variables are set:

$&

The string that matched.

$`

The string preceding what was matched.

$'

The string following what was matched.

$1

The first parenthesized subexpression that matched, $2 the second, and so on.

$+

The last subexpression that matched.

@-

The start offsets of the match and submatches.

@+

The corresponding end offsets.

If used in list context, a list is returned consisting of the subexpressions matched by the parentheses in pattern, i.e., ($1,$2,$3, . . . ).

Optional modifiers are:

c

(with g) prepares for continuation.

g

matches as many times as possible.

i

searches in a case-insensitive manner.

o

interpolates variables only once.

m

treats the string as multiple lines. ^ and $ will match at embedded newline characters.

s

treats the string as a single line. . will match embedded newline characters.

x

allows for whitespace and comments.

If pattern is empty, the most recent pattern from a previous successful m// or s/// is used.

With g, the match in scalar context can be used as an iterator. The iterator is reset upon failure, unless c is also supplied.

See generic Chapter 6.

?pattern?

This is just like the /pattern/ search, except that it matches only once between calls to the reset operator.

[ $var =~ ] s /pattern ...

Get Perl Pocket Reference, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.