Smartmatch Operator
First available in v5.10.1,[63] binary ~~ does a
“smartmatch” between its arguments. This is mostly used implicitly in the
when construct, although not all
when clauses call the smartmatch
operator. Unique among all of Perl’s operators, the smartmatch operator
can recurse.
It is also unique in that all other Perl operators impose a context (usually string or numeric context) on their operands, autoconverting those operands to those imposed contexts. In contrast, smartmatch infers contexts from the actual types of its operands and uses that type information to select a suitable comparison mechanism.
The ~~ operator compares its
operands “polymorphically”, determining how to compare them according to
their actual types (numeric, string, array, hash, and so on). Like the
equality operators with which it shares the same precedence, ~~ returns 1 for true and "" for false. Much like the =~ binding operator, this operator’s right
argument is considered to be a pattern that either accepts or rejects the
left argument. However, the notion of “pattern” is generalized greatly,
and nearly any value can function as a pattern, or as a list of
patterns.
So ~~ is often best read aloud as
“matches” or “matches any of”, because the left operand submits itself to
be accepted or rejected by the right operand (or some part of the right
operand).
The behavior of a smartmatch depends on what type of things its arguments are, as determined by Table 3-7. The first row of the table whose ...
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.
Read now
Unlock full access