Regular Expressions

Regular expressions are used several ways in Perl. They’re used in conditionals to determine whether a string matches a particular pattern. They’re also used to find patterns in strings and replace the match with something else.

The ordinary pattern match operator looks like / pattern /. It matches against the $_ variable by default. If the pattern is found in the string, the operator returns true (1); if there is no match, a false value (“”) is returned.

The substitution operator looks like s/ pattern / replace /. This operator searches $_ by default. If it finds the specified pattern, it is replaced with the string in replace. If pattern is not matched, nothing happens.

You may specify a variable other than $_ with the =~ binding operator (or the negated !~ binding operator, which returns true if the pattern is not matched). For example:

$text =~ /sampo/;

Get Perl in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.