Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ~~ a short-circuit operator?

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.) ?

like image 466
Eugene Yarmash Avatar asked Dec 27 '25 16:12

Eugene Yarmash


2 Answers

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) }"
like image 58
Lumi Avatar answered Dec 31 '25 19:12

Lumi


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 ||.

like image 34
LHMathies Avatar answered Dec 31 '25 19:12

LHMathies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!