3

From the Smart matching in detail section in perlsyn:

The smart match operator short-circuits whenever possible.

Does ~~ have anything in common with short circuit operators (&&, ||, etc.) ?

ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378

2 Answers2

4

The meaning of short-circuiting here is that evaluation will stop as soon as the boolean outcome is established.

perl -E "@x=qw/a b c d/; for (qw/b w/) { say qq($_ - ), $_ ~~ @x ? q(ja) : q(nein) }"

For the input b, Perl won't look at the elements following b in @x. The grep built-in, on the other hand, to which the document you quote makes reference, will process the entire list even though all that's needed might be a boolean.

perl -E "@x=qw/a b c/; for (qw/b d/) { say qq($_ - ), scalar grep $_, @x ? q(ja) : q(nein) }"
Lumi
  • 14,775
  • 8
  • 59
  • 92
4

Yes, in the sense that when one of the arguments is an Array or a Hash, ~~ will only check elements until it can be sure of the result.

For instance, in sub x { ... }; my %h; ...; %h ~~ \&x, the smart match returns true only if x returns true for all the keys of %h; if one call returns false, the match can return false at once without checking the rest of the keys. This is similar to the && operator.

On the other hand, in /foo/ ~~ %h, the smart match can return true if it finds just one key that matches the regular expression; this is similar to ||.

LHMathies
  • 2,384
  • 16
  • 21