Binding Operators
Binary =~
binds a string expression
to a pattern match, substitution, or transliteration (loosely called
translation). These operations would otherwise search or modify the
string contained in $_
(the default variable). The
string you want to bind is put on the left, while the operator itself
is put on the right. The return value indicates the success or failure
of the operator on the right, since the binding operator doesn't
really do anything on its own.
If the right argument is an expression rather than a pattern
match, substitution, or transliteration, it will be interpreted as a
search pattern at run time. That is to say, $_ =~
$pat
is equivalent to $_ =~ /$pat/
. This
is less efficient than an explicit search, since the pattern must be
checked and possibly recompiled every time the expression is
evaluated. You can avoid this recompilation by precompiling the
original pattern using the qr//
(quote regex)
operator.
Binary !~
is just like
=~
except the return value is negated logically.
The following expressions are functionally equivalent:
$string !~ /pattern/ not $string =~ /pattern/
We said that the return value indicates success, but there are many kinds of success. Substitutions return the number of successful matches, as do transliterations. (In fact, the transliteration operator is often used to count characters.) Since any nonzero result is true, it all works out. The most spectacular kind of true value is a list assignment of a pattern: in a list context, ...
Get Programming Perl, 3rd 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.