Perl 中的“||”如何工作?
||
在 Perl 中如何工作?我想实现c风格的||
操作。
@ARRAY=qw(one two THREE four);
$i=0;
if(($ARRAY[2] ne "three")||($ARRAY[2] ne "THREE")) #What's the problem with this
{
print ":::::$ARRAY[2]::::::\n";
}
while(($ARRAY[$i] ne "three")||($ARRAY[$i] ne "THREE")) #This goes to infinite loop
{
print "->$ARRAY[$i]\n";
$i=$i+1;
}
How does the ||
works in Perl? I want to achieve c style ||
operation.
@ARRAY=qw(one two THREE four);
$i=0;
if(($ARRAY[2] ne "three")||($ARRAY[2] ne "THREE")) #What's the problem with this
{
print ":::::$ARRAY[2]::::::\n";
}
while(($ARRAY[$i] ne "three")||($ARRAY[$i] ne "THREE")) #This goes to infinite loop
{
print "->$ARRAY[$i]\n";
$i=$i+1;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它的工作原理与您想象的完全一样。然而,你对你的情况有一个想法。每个值要么不是一个值,要么不是另一个值。
我相信您可能想要
或者
您可能还想要某种不区分大小写的比较方式,例如
或可能是不区分大小写的正则表达式匹配。
It works exactly the way you thought it would. However, you have a thinko in your condition. Every value is either not one value or not another value.
I believe you might have wanted
or
You might also want some case-insensitive way of comparing, like
or possibly a case-insensitive regexp match.
两个一般要点。 (1) 您的 Perl 脚本应包含
use strict
和use warnings
。 (2) 在大多数情况下,您可以直接迭代数组,完全避免使用下标。一个例子:Two general points. (1) Your Perl scripts should include
use strict
anduse warnings
. (2) In most situations, you can iterate directly over an array, avoiding subscripts entirely. An example:在
($ARRAY[2] ne "三") || 中($ARRAY[2] ne "THREE")
||
是一个逻辑or
,这意味着如果两个表达式中至少有一个则返回 true是真的。好吧,它会检查第一个,如果它是真的,它甚至不会检查第二个。在这种情况下,无论如何,整体都是 true,因为$ARRAY[2]
不能等于两个字符串。嗯,就像 CI 相信的那样。您想实现什么目标?
In
($ARRAY[2] ne "three") || ($ARRAY[2] ne "THREE")
the||
is a logicalor
, which means it returns true if at least one of the two expressions is true. Well, it checks the first one and if it is true, it even does not check the second one. And in this case the whole will be true anyway, since$ARRAY[2]
cannot be equal to both strings.Well, it is just like in C I believe. What would you like to achieve?
while(($ARRAY[$i] ne "third")||($ARRAY[$i] ne "THREE"))
:表达式
$ARRAY[$i] ne "三”
始终评估为 true。因此你有一个无限循环。||
运算符具有短路行为,因此永远不会计算第二个表达式。while(($ARRAY[$i] ne "three")||($ARRAY[$i] ne "THREE"))
:the expression
$ARRAY[$i] ne "three"
always evaluates to true. Therefore you have an infinite loop. The||
operator has short-circuit behavior so the second expression is never evaluated.在任何情况下都是如此。要么不是“三”,要么不是“三”。您需要
&&
。This is going to be true in every case. It's either going to be not "three" or not "THREE". You want
&&
.