[Chapter 15] 15.14 Search and Replace Functions
Author: Stephen Spainhour and Valerie Quercia
Date: Fri Aug 29 18:13:16 1997

#

| Chapter 15 Perl Quick Reference |

## 15.14 Search and Replace Functions

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

  Searches expr (default: $_) for a pattern. If you prepend an `m` you can use almost any pair of delimiters instead of the slashes. If used in array context, an array is returned consisting of the subexpressions matched by the parentheses in the pattern, i.e., ($1, $2, $3,...). Optional modifiers: `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; `s` treats the string as a single line; `x` allows for regular expression extensions. If pattern is empty, the most recent pattern from a previous match or replacement is used. With `g` the match can be used as an iterator in scalar context.

?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; if no substitutions are made, 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 /pattern/ matching. Almost any delimiter may replace the slashes; if 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, pattern and replacement may have their own delimiters, e.g., s(foo)[bar]. If pattern is empty, the most recent pattern from a previous match or replacement is used.

"[

  Translates all occurrences of the characters found in the search list with the corresponding character in the replacement list. It returns the number of characters replaced. `y` may be used instead of `tr`. Optional modifiers: `c` complements the searchlist; `d` deletes all characters found in searchlist that do not have a corresponding character in replacementlist; `s` squeezes all sequences of characters that are translated into the same target character into one occurrence of this character.

`pos` scalar

  Returns the position where the last `m`/ /`g` search left off for scalar. May have a value assigned to it.

`study` [ $var(dagger) ]

  Studies the scalar variable $var in anticipation of performing many pattern matches on its contents before the variable is next modified.

Regular Expressions |  | File Test Operators