Skip to Content
Learning Perl, 6th Edition
book

Learning Perl, 6th Edition

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

Chapter 15. Smart Matching and given-when

Wouldn’t it be great if computers could just figure out what you wanted and do that? 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 multiple items. With Perl 5.10’s smart match operator and given-when control structure, it gets even better.

Smart matching showed up in Perl 5.10.0, but in a broken form. That’s not a big deal because most of the problems disappeared in Perl 5.10.1. (That means that you may need an updated version for this chapter.) Don’t even consider using smart matching in Perl 5.10.0. It will just cause problems later. As such, we’re going to be much more specific about the Perl version in this chapter by specifying the point release version to remind you to use an appropriate version:

use 5.010001;  # at least 5.10.1

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

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

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 9781449311063Errata PageSupplemental Content