Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

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. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page