문제

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.

다른 팁

That's how the && operator works: if the left-hand argument evaluates as true, the value of the expression is that of the value of the right-hand argument. This is covered on the perlop page.

However, you've also let yourself open to a much more subtle problem. You'll find that the newline doesn't get printed. This is because if you put an expression in brackets after print (or any other function name) the arguments passed to print are just those in the brackets. To get notice of this, make sure you switch on warnings. Put these lines at the top of each program:

#!/usr/bin/perl -w

use strict;

until you understand them enough to decide for yourself whether to continue with them. :-)

In your case, you'll get this:

print (...) interpreted as function at p line 7.
Useless use of concatenation (.) or string in void context at p line 7.

Because the && operator evaluates the right operand and returns the result when the left operand evaluates to true.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top