When I try this:
$a = 1;
$b = 2;
print ($a && $b) . \"\\n\";
The result is 2. Why?
Quote perlop:
The "||", "//" and "&&" operators return the last value evaluated (unlike C's "||" and "&&", which return 0 or 1).
The resulting 2
is considered true by Perl, so that when you use the &&
operator in a logical condition, everything works as expected. The added bonus is that you can use the logical operators in other contexts as well:
sub say_something {
say shift || 'default';
}
say_something('foo'); # prints 'foo'
say_something(); # prints 'default'
Or even as flow modifiers:
my $param = shift || die "Need param!";
-f $file && say "File exists.";
In the last two examples it’s good to realize that they could not work if the &&
and ||
operators did not short-circuit. If you shift
a true value in on first line, there is no point evaluating the right side (die…
), since the whole expression is true anyway. And if the file test fails on the second line, you don’t need to evaluate the right side again, since the overall result is false. If the logical operators insisted on evaluating the whole expression anyway, we could not use them this way.