6

当我尝试这个时:

$a = 1;
$b = 2;
print ($a && $b) . "\n";

结果是 2。为什么?

4

3 回答 3

15
于 2010-10-24T09:43:28.110 回答
11

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.
于 2010-10-24T09:47:25.063 回答
2

因为&&运算符计算右操作数并在左操作数计算为真时返回结果。

于 2010-10-24T09:41:40.717 回答