Eugene Yarmash
Eugene Yarmash

Reputation: 149813

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

Upvotes: 3

Views: 376

Answers (2)

LHMathies
LHMathies

Reputation: 2434

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

Upvotes: 4

Lumi
Lumi

Reputation: 15274

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) }"

Upvotes: 4

Related Questions