O'Reilly logo

Perl Pocket Reference, 5th Edition by Johan Vromans

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

Smartmatching

Note: Smartmatching is a relatively new feature and several aspects of its peculiar behavior may change in subsequent Perl releases.

expr1 ~~ expr2

Smartmatches expr2 against expr1.

when ( expr )

In most cases, smartmatches $_ against expr.

In other cases, treats expr as a boolean expression.

The behavior of a smartmatch depends on what type of thing its arguments are. The behavior is determined by the following table: the first row that applies determines the match behavior (which is thus mostly determined by the type of the right operand). Note that the smartmatch implicitly dereferences any nonblessed hash or array ref, so the Hash and Array entries apply in those cases. For blessed references, the Object entries apply.

Left

Right

Type of match implied

Any

undef

Undefinedness.

Any

Object

Invokes ~~ overloading on the object, or dies.

Hash

CodeRef

Sub truth for each key; true if hash is empty.

Array

CodeRef

Sub truth for each element; true if array is empty.

Any

CodeRef

Scalar sub truth.

Hash

Hash

True if every key is found in both hashes.

Array

Hash

Hash keys intersection.

Regex

Hash

Hash key grep.

undef

Hash

Always false.

Any

Hash

Hash entry existence.

Hash

Array

Hash Keys Intersection.

Array

Array

Smartmatches corresponding elements.

Regex

Array

Array grep.

undef

Array

Array contains undef.

Any

Array

Match against an array element.

Hash

Regex

Hash key grep.

Array

Regex

Array grep.

Any

Regex

Pattern match.

Object

Any

Invokes ~~ overloading on the object, or falls back.

Any

Num

Numeric equality.

Num

Num-alike

Numeric equality if it ...

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