O'Reilly logo

Learning Perl, 6th Edition by Tom Phoenix, Randal L. Schwartz, brian d foy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required