我的 Perl 脚本中的 if-elsif-else 块有什么问题?
我正在尝试为嵌套 if 语句编写条件,但尚未找到使用 or in if 语句的好示例。以下 elsif
条件失败,并允许嵌套在其下面的代码在 $status == 6
时触发:
if ($dt1 > $dt2 ) {do one thing}
elsif(($status != 3) || ($status != 6)) { do something else}
else {do something completely different}
我想避免为每个条件使用另一个 elsif 作为代码实际上驻留在此处的内容有几行长。
I'm trying to write a condition for a nested if statement, but haven't found a good example of using or in if statements. The following elsif
condition fails and allows the code nested beneath it to fire if $status == 6
:
if ($dt1 > $dt2 ) {do one thing}
elsif(($status != 3) || ($status != 6)) { do something else}
else {do something completely different}
I'd like to avoid having another elsif for each condition as the code that actually resides here is several lines long.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的逻辑是错误的,你的 elseif 块将始终返回 true。我认为您的意思是使用 AND 而不是 OR。给定以下代码片段,
这将输出
If it help your think, 条件语句是 !something || !somethingElse 始终可以重写为 !(something && someElse)。如果你将此应用于上面的情况,你会说 !(3 && 6),并且由于数字不能同时是 3 和 6,因此它总是错误的
Your logic is wrong and your elseif block will always return true. I think you mean to use an AND instead of an OR. Given the following snippet
This will output
If it helps your thinking, a conditional that is !something || !somethingElse can always be rewritten as !(something && somethingElse). If you apply this to your case above you'd say !(3 && 6), and seeing as a number cannot be 3 and 6 at the same time, it's always false
你说你问这个是因为代码有几行长。解决这个问题。 :)
现在块中没有几行,并且所有内容都彼此相邻。您必须弄清楚这些条件是什么,因为任何值要么不是 3,要么不是 6。:)
也许您打算使用
and
:You said you're asking this because the code is several lines long. Fix that problem. :)
Now you don't have several lines in the block and everything is next to each other. You have to figure out what those conditions will be because any value is either not 3 or not 6. :)
Perhaps you meant to use
and
:将带有 var 名称/值的
print
语句放入每个分支会很有帮助。您可以看到
elsif
分支始终运行,因为$status != 3 || $status != 6
对于$status
的任何值都为 true。Putting
print
statements with var names/values into each branch can be helpful.You could see that the
elsif
branch is always run, because$status != 3 || $status != 6
is true for any value of$status
.