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

Smart Match Precedence

Now that you’ve seen how the smart match operator can save you a lot of work, you just need to know how to tell which sort of match it will do. For that you have to check the table in the perlsyn documentation under “Smart matching in detail.” Table 15-1 shows some of the things the smart match operator can do.

Table 15-1. Smart match operations for pairs of operands

Example

Type of match

%a ~~ %b

Hash keys identical

%a ~~ @b

At least one key in %a is in @b

%a ~~ /Fred/

At least one key matches pattern

%a ~~ 'Fred'

Hash key existence exists $a{Fred}

  

@a ~~ @b

Arrays are the same

@a ~~ /Fred/

At least one element matches pattern

@a ~~ 123

At least one element is 123, numerically

@a ~~ 'Fred'

At least one element is 'Fred', stringwise

  

$name ~~ undef

$name is not defined

$name ~~ /Fred/

Pattern match

123 ~~ '123.0'

Numeric equality with “numish” string

'Fred' ~~ 'Fred'

String equality

123 ~~ 456

Numeric equality

When you use the smart match operator, Perl goes to the top of the chart and starts looking for a type of match that corresponds to its two operands. It then does the first type of match it finds. The order of the operands doesn’t matter. For instance, you have an array and a hash with the smart match:

use 5.010;

if( @array ~~ %hash ) { ... }

Perl first finds the match type for a hash and an array, which checks that at least one of the elements of @array is a key in %hash. That one is easy because there is only one type of match for those two operands. What ...

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