在比较条件时使用逻辑运算符AND OR

时间:2014-11-20 23:54:09

标签: perl conditional-statements logical-operators

我对逻辑运算符&&,和||,或的使用(以及我猜的返回值)存在疑问。

$number = 5; 
$numberA = 5;
$numberB = 1;

$string = "x"; 
$stringA = "x";
$stringB = "y";

If two numbers are compared:
$x=5;   
if ( $x == $number ) { print '$x == $number', "\n"; }


If two strings are compared:
$x="x";
if ( $x eq $string ) { print '$x eq $string', "\n"; }

但我不确定将两个数字/字符串计算为数字/字符串的最佳方法是什么。这是对的吗?

$x=5; $y=5;
if ( ($x && $y) == $number ) { print '($x && $y) == $number', "\n"; }


$x="x"; $y="x";
if ( ($x and $y) eq $string ) { print '($x and $y) eq $string', "\n"; }

当两个逻辑在相​​同条件下被评估时,规则是什么?是否应将条件本身作为数字(&&,||)或字符串(和,或)进行比较?

$x=5; $y=1;
if ( ($x == $numberA) && ($y == $numberB) ) { print '&& or and here?', "\n"; }

$x="x"; $y="y";
if ( ($x eq $stringA) and ($y eq $stringB) ) { print 'and or or here?', "\n"; }

1 个答案:

答案 0 :(得分:2)

( $foo && $bar ) == $baz

不按照你的想法行事;它首先评估&&操作,如果$foo为真,则获取$foo的值,否则获得$bar的值,然后将其与$baz进行比较。您需要明确拼写为$foo == $baz && $bar == $baz来测试它们。

如果你有很多值(最好是在一个数组中,而不是一堆单独的变量),grep会很有用:

if ( 2 == grep $_ == $baz, $foo, $bar ) {

List :: MoreUtils也提供了方便的all方法:

use List::MoreUtils 'all';
if ( all { $_ == $baz } $foo, $bar ) {

and / or&& / ||不是字符串或数字运算符;字母的功能与等效的符号功能完全相同。唯一的区别是他们有不同的优先权; && / ||具有更高的优先级,因此它们在表达式中非常有用; and / or具有较低的优先级,因此它们对于本质上不同的表达式之间的流控制很有用。一些例子:

my $x = $y || 'default_value';

相当于:

my $x = ( $y || 'default_value' );

VS

my @a = get_lines() or die "expected some lines!";

相当于:

( my @a = get_lines() ) or die "expected some lines!";