C.W.Holeman II C.W.Holeman II - 2 months ago 7
Perl Question

What does " ~~ " mean in Perl?

In an SO answer daxim states:


@array ~~ $scalar is true when $scalar is in @array



to which draegtun replies:


From 5.10.1+ the order of ~~ is
important. Thus it needs to be $scalar
~~ @array


How about a small primer on
~~
with link(s) to source(s) including the following specific questions: What is
~~
? What is
~~
called? Why does the order matter in one version but not in a previous one?

Note that a good summary may not get all the details and can be hard to write. An introduction or primer would be very useful to save time for someone unfamiliar with
~~
while expanding the exposure of this Perlism.

Search strings:
non-word-tilde-tilde
non-word-at-sign
.

Answer

Answering specifically "why does the order matter in one version but not in a previous one": the smart match operator was badly designed in 5.10.0 in a way that made it difficult to use reliably, and made the given/when construct less useful than it could be, so the semantics were changed with 5.10.1 and all future versions will pretend that the 5.10.0 version never existed.

In the 5.10.1+ version of smart match, the left operand and the right operand to ~~ are always treated distinctly. Just as with the =~ regex match operator, the left side is the "subject" of the match, and the right side is the "pattern" to match against -- whether that be a plain scalar, a regex, an array or hash reference, a code reference, or whatever. The specifics are detailed pretty well in perlsyn.

You shouldn't worry about the 5.10.0 version at all unless you've already written code that depends on the 5.10.0 semantics (in which case, you should rewrite it to require 5.10.1, or else it will break on all future versions of perl).

Comments