Book Home Programming PerlSearch this book

3.6. 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, pattern matches can return substrings matched by the parentheses in the pattern. But again, according to the rules of list assignment, the list assignment itself will return true if anything matched and was assigned, and false otherwise. So you sometimes see things like:
if ( ($k,$v) = $string =~ m/(\w+)=(\w*)/ ) {
    print "KEY $k VALUE $v\n";
}
Let's pick that apart. The =~ has precedence over =, so =~ happens first. The =~ binds $string to the pattern match on the right, which is scanning for occurrences of things that look like KEY=VALUE in your string. It's in a list context because it's on the right side of a list assignment. If the pattern matches, it returns a list to be assigned to $k and $v. The list assignment itself is in a scalar context, so it returns 2, the number of values on the right side of the assignment. And 2 happens to be true, since our scalar context is also a Boolean context. When the match fails, no values are assigned, which returns 0, which is false.

For more on the politics of patterns, see Chapter 5, "Pattern Matching".



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.