Perl Cheat Sheet Page 15

ADVERTISEMENT

16. Search and replace functions
[
=˜ ] [
] /
/ [
]
EXPR
m
PATTERN
c g i m o s x
Searches
(default: $_ ) for a pattern. If you prepend an
you can use
EXPR
m
almost any pair of delimiters instead of the slashes. If used in array context,
an array is returned consisting of the sub-expressions matched by the
parentheses in pattern, i.e. ($1,$2,$3, . . . ) .
Optional modifiers:
continues the previous match (use with
);
matches
c
g
g
as many times as possible;
searches in a case-insensitive manner;
i
o
interpolates variables only once.
let ‘ ˆ ’ and ‘ $ ’ match even at embedded newline characters;
let ‘ . ’
m
s
match even at embedded newline characters;
x
allows for regular expression
extensions.
If
PATTERN
is empty, the most recent pattern from a previous successful
match or replacement is used.
With
the match can be used as an iterator in scalar context. The iterator is
g
reset upon failure, unless
c
is also supplied.
PATTERN
?
?
This is just like the /
PATTERN
/ search, except that it matches only once
between calls to the
reset
operator.
[ $
VAR
=˜ ]
s
PATTERN
REPLACEMENT
/ [
e g i m o s x
]
/
/
Searches a string for a pattern, and if found, replaces that pattern with the
replacement text. It returns the number of substitutions made, if any,
otherwise it returns false.
Optional modifiers:
g
replaces all occurrences of the pattern;
e
evaluates the
replacement string as a Perl expression; for the other modifiers, see
/ matching. Almost any delimiter may replace the slashes; if
/
PATTERN
single quotes are used, no interpolation is done on the strings between the
delimiters, otherwise the strings are interpolated as if inside double quotes.
If bracketing delimiters are used,
and
may have
PATTERN
REPLACEMENT
their own delimiters, e.g. s(foo)[bar] .
If
is empty, the most recent pattern from a previous successful
PATTERN
match or replacement is used.
[ $
=˜ ]
/ [
]
VAR
tr
/
SEARCHLIST
/
REPLACEMENTLIST
c d s
Translates all occurrences of the characters found in the search list into the
corresponding character in the replacement list. It returns the number of
characters replaced.
may be used instead of
.
y
tr
Optional modifiers:
c
complements the
SEARCHLIST
;
d
deletes all
characters found in
that do not have a corresponding
SEARCHLIST
character in
REPLACEMENTLIST
;
s
squeezes all sequences of characters
that are translated into the same target character into one occurrence of this
character.
y ]
pos
[
SCALAR
Returns the position where the last
m
g
search left off for
SCALAR
. May
//
be assigned to.
y ]
study
[ $
VAR
Studies the scalar variable $
VAR
in anticipation of performing many pattern
matches on its contents before the variable is next modified.
15

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education