Chapter 15. Smart Matching and given-when

Wouldn’t it be great if computers could just figure out what you wanted and do it? Perl already does its best to use numbers when you want numbers, strings when you want strings, single values where you mean a single value, and lists when you mean lists. With Perl 5.10’s smart match operator and given-when control structure, it gets even better.

The Smart Match Operator

The smart match operator, ~~, looks at both of its operands and decides on its own how it should compare them. If the operands look like numbers, it does a numeric comparison. If they look like strings, it does a string comparison. If one of the operands is a regular expression, it does a pattern match. It can also do some complex tasks that would otherwise take a lot of code, so it keeps you from doing too much typing.

The ~~ looks almost like the binding operator, =~, which you saw in Chapter 8, but ~~ can do much more. It can even stand in for the binding operator. Up to now, you’d match a pattern by using the binding operator to associate $name with the regular expression operator:

print "I found Fred in the name!\n" if $name =~ /Fred/;

Now, you can change that binding operator to the smart match operator and do exactly the same thing:

use 5.010;

say "I found Fred in the name!" if $name ~~ /Fred/;

The smart match operator sees that it has a scalar on the lefthand side and the regular expression operator on the righthand side, and figures out on its own to do the pattern match. ...

Get Learning Perl, 5th 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.