“if”的用法与“除非”相对对于 Perl 条件语句

发布于 2024-09-05 23:27:20 字数 90 浏览 5 评论 0原文

在 Perl 代码中最佳使用 ifunless 的指导原则是什么?在某些情况下是否有充分的理由选择其中之一?

What are some guidelines for the best use of if versus unless in Perl code? Are there strong reasons to prefer one or the other in some situations?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

深海蓝天 2024-09-12 23:27:20

在 Perl 最佳实践中,建议永远不要使用 unless。就我个人而言,我认为这是疯狂的。

每当有一个简单的条件时,我都会使用 unless,否则我会写成 if( ! ... )。我发现 unless 版本更具可读性,尤其是用作后缀时:

do_something() unless $should_not_do_that;

我建议在事情变得更加复杂时避免 unless ,例如当您将 elsifelse 块。 (幸运的是,或者不幸的是,根据您的观点,没有 elsunless

此外,任何时候条件都是由其他布尔值组成的复杂表达式。例如,

unless( $foo and !$bar )

非常令人困惑,并且与等效的 if 相比没有任何优势。

In Perl Best Practices, the advice is to never use unless. Personally, I think that's lunacy.

I use unless whenever there's a simple condition that I would otherwise write as if( ! ... ). I find the unless version to be more readable, especially when used as a postfix:

do_something() unless $should_not_do_that;

I recommend avoiding unless anytime things get more complicated, such as when you will have elsif or else blocks. (Fortunately, or perhaps unfortunately, depending on your perspective, there is no elsunless)

Also, any time a conditional is a complex expression made up of other booleans. For example,

unless( $foo and !$bar )

Is pretty damn confusing, and does not have any advantage over the equivalent if.

拥醉 2024-09-12 23:27:20

除了一种深奥的情况1 unless 只是 if ! 的语法糖。它的存在是为了让您编写更清晰、更具表现力的代码。当它实现这个目标时就应该使用它,当它损害它时就应该避免它。

我发现 unless 对于循环中的流量控制最有用。例如,

while (<$fh>) {
    next unless /\S/;
    # ...
}

对于简单的否定,我发现它比否定的 if 更清晰——在阅读代码时很容易错过前导的 !

unless ($condition) {
    do_something();
}

if (!$condition) {
    do_something();
}

但不要写unless ... else,因为那样会很刺耳。

它以后缀形式提供了有关代码的预期路径的提示。

do_normal_thing() unless $some_unlikely_condition;


1) The last expression evaluated is different, which can affect the behavior of subs without an explicit return.

Aside from one esoteric case1 unless is just syntactic sugar for if !. It exists to allow you to write code that is clearer and more expressive. It should be used when it achieves this goal and shunned when it impairs it.

I find unless to be most useful for flow control in loops. e.g.

while (<$fh>) {
    next unless /\S/;
    # ...
}

For simple negations I find it clearer than a negated if -- it's easy to miss that leading ! when reading code.

unless ($condition) {
    do_something();
}

if (!$condition) {
    do_something();
}

But don't write unless ... else, because that's just jarring.

In postfix form it provides a hint about what the expected path through the code is.

do_normal_thing() unless $some_unlikely_condition;


1) The last expression evaluated is different, which can affect the behavior of subs without an explicit return.

ぶ宁プ宁ぶ 2024-09-12 23:27:20

经验法则是“除非”可能不应该经常使用。

它在后缀形式中特别有用,例如:

delete_old_widgets() unless $old_widget_count == 0

永远不应该使用 except 的情况:

  • 与复合条件(and、or、not)
  • 和 else 子句一起使用

A rule of thumb is that 'unless' should probably be used infrequently.

It is particularly useful in the postfix form, e.g.:

delete_old_widgets() unless $old_widget_count == 0

Situations where you should never use unless:

  • with a compound condition (and, or, not)
  • with an else clause
羁〃客ぐ 2024-09-12 23:27:20

我最近花了一个小时试图向某人解释两个嵌套的“除非”子句是如何工作的,如果不将它们反转为带有布尔逻辑的 if 语句,就很难破译。

如果您尝试将其转换为英语,它将有助于指导您。

一个简单的除非工作正常。例如。

“除非你安静,否则我会忽略你”。

unless ($quiet) {
    ignore();
}

虽然我认为这同样有效

,“如果你不安静,我就会忽略你”,但当

if (not $quiet) {
    ignore();
}

事情开始变得复杂时,就是你否定的时候。

“除非你不吵闹,否则我会忽略你”

unless ( ! $noisy) {
    ignore();
}

更好地写成

“如果你吵闹,我会忽略你”

if ($noisy) {
    ignore();
}

因此,如果你也有否定,请不要使用“除非”。

也不要使用“除非其他”

unless ($quiet) {
    ignore();
}
else {
    give_a_sweet();
}

“除非你安静,我会忽略你,否则我会给你一个甜蜜”

通过反转条件来更改它。

if ($quiet) {
    give_a_sweet();
}
else {
    ignore();
}

“如果你安静,我就给你一颗糖,否则我就不理你了”。

如果条件不止一个,事情就会变得混乱。

unless ($quiet and not $fidgit) {
    punish();
}

“除非你安静并且不坐立不安,否则我会惩罚你”。

(抱歉,我的理解力在这里失败了!)

再次否定它。

if (not $quiet or $fidgit) {
    punish();
}

“如果你不安静,或者你烦躁,我会惩罚你”。

即使对于最简单的情况,使用“除非”的问题也经常发生(

我希望自己或别人清楚地表明您何时应该或不应该使用除非?

(除非您没有其他意见?)

I spent an hour recently trying to explain to someone how two nested 'unless' clauses worked, it was difficult to decypher without having to invert them into if statements with boolean logic.

If you try to convert it into English, it helps to guide you.

A simple unless works fine. For example.

'Unless you are quiet, I am going to ignore you'.

unless ($quiet) {
    ignore();
}

Although I think this works equally well

'If you are not quiet, I am going to ignore you'

if (not $quiet) {
    ignore();
}

when it starts getting complicated is when you have negation.

'Unless you are not noisy, I am going to ignore you'

unless ( ! $noisy) {
    ignore();
}

Far better written as

'If you are noisy, I am going to ignore you'

if ($noisy) {
    ignore();
}

So, don't use an 'unless' if you also have a negate.

Also don't use 'unless else'

unless ($quiet) {
    ignore();
}
else {
    give_a_sweet();
}

'Unless you are quiet, I will ignore you, otherwise I will give you a sweet'

Change it by inverting the condition.

if ($quiet) {
    give_a_sweet();
}
else {
    ignore();
}

'If you are quiet, I will give you a sweet, otherwise I will ignore you'.

with more than one condition, it get's messy.

unless ($quiet and not $fidgit) {
    punish();
}

'Unless you are quiet and you don't fidgit, I will punish you'.

(sorry my comprehension is failing here!)

again, negate it.

if (not $quiet or $fidgit) {
    punish();
}

'If you are not quiet, or you fidgit, I will punish you'.

the problem with using 'unless' even for the simplest cases, they often (by yourself or by outhe

I hope that makes it clear when you should, or should not, use unless?

(unless you don't have another opinion?)

温暖的光 2024-09-12 23:27:20

虽然我理解这类问题的动机,但我不认为将诸如 unless 之类的东西的使用归结为具体的经验法则是不明智的。这就像 Perl 中的许多辅助语法一样,是为程序员提供一个小小的便利,帮助他们根据自己的判断更清楚地表达自己;我在《Programming Perl》中看到了首席开发人员以多种方式表达的内容。没有更高的目的或合理化。我很清楚这巧妙地解决了这个问题,但我对使用它施加的唯一限制是看到它服务于更广泛的目的,即使代码更清晰。如果是这样,那么一切都好。识别代码是否可理解本身是直观的,并且不能简化为大量过度概括的使用条件,涉及内置修饰符/运算符/整体语法的每个细微差别,以及大型团体项目中需要约束和指南的地方我认为把头发分得这么细是没有意义的。

Though I understand the motivations for these sorts of questions I don't believe it's really sensible to boil down the use of something like unless into concrete rules of thumb. This, like a lot of auxiliary syntax in Perl is provided as a minor convenience for programmers to help them articulate themselves clearer at their own discretion; I've seen as much said in more ways than one by the lead developers throughout "Programming Perl". There's no higher purpose or rationalization. I'm well aware this finesses the question, but the only constraint I'd impose on using it is to see that it serves its broader purpose of making the code clearer. If it does, then all is well. Recognizing whether code is understandable is intuitive in itself and can't be reduced to a large handful of overly generalized usage conditions concerning every nuance of the built-in modifiers/operators/overall syntax, and where constraints and guidelines are needed in large group projects I don't think it would make sense to split hairs this finely.

乞讨 2024-09-12 23:27:20

我的意见是永远不要使用除非。我的理由是:

  • 我认为语法使代码更难以阅读。使用单一方法执行 if 会使事情变得更简单、更一致。
  • 如果稍后需要添加 else 语句,则应该将 except 更改为 if。如果它已经是一个 if,那就更容易了。
  • 如果 except 语句内的逻辑变得更加复杂,那么您最终可能会得到奇怪的代码,例如“unless (x == 5 && y != 7)”。这很奇怪,因为第二次检查有双重否定。
  • 还有其他方法可以否定事物,即 x != 5
  • 有一个很好的理由。

它与其他语言更加一致,我不知道有任何其他语言有 except 语句,我认为在 perl 中 实际上有 4 种编写 if 语句的方法,if,unless,然后将检查放在行尾而不是开头。我更喜欢与其他语言一致的单一一致方法,也

只值我的 0.02 美元。

My opinion would be to never use unless. My reasons are:

  • I think the syntax makes code more difficult to read. Having a single method of doing an if makes thing simpler and more consistent.
  • If you need to add an else statement later on you should really change the unless to an if. It's just easier if it is already an if.
  • If the logic inside the unless statement becomes more complex then you can end up with odd code like "unless (x == 5 && y != 7). This is odd because there is a double negative on the second check.
  • There are other ways to negate things, ie x != 5
  • It's more consistent with other languages. I don't know of any other language that has an unless statement and I think there is a very good reason for this.

In perl there are really 4 ways to write an if statement, if, unless and then putting the check at the end of the line instead of the start. I much prefer a single consistent method that is consistent with other langauges also.

Just my $0.02 worth.

紅太極 2024-09-12 23:27:20

恰如其分...

在 Perl 最佳实践中,建议永远不要使用 except。亲自,
我认为这太疯狂了。

20 多年来,我更喜欢 Perl 而不是它的任何替代品(如果没有 Perl 提供模板,大多数替代品都不会存在),我不仅同意“疯狂”的判决,而且我很惊讶(担心)听到“最佳实践” '想要摆脱它。

也就是说,我强烈喜欢为了清晰而编写的代码,而不是一些 Perl 程序员“仅仅因为他们可以”而采用隐式混淆的替代方案。 “unless”是“if”的明确反义词,因此是在“if”条件中嵌入否定的非常有用的替代方法,特别是当条件包含多个运算符时。即使后面跟着 else/elsif,这个基本原理也适用。

Apropos...

In Perl Best Practices, the advice is to never use unless. Personally,
I think that's lunacy.

After 20+ years preferring Perl over any of its alternatives (most of which would not exist had not Perl provided the template), I not only concur with the 'lunacy' verdict, I'm surprised (concerned) to hear that 'Best Practices' wants to get rid of it.

That said, I strongly prefer code written for clarity, as opposed to the implicitly obfuscated alternatives some Perl programmers adopt 'just because they can'. 'unless' is the unambiguous opposite of 'if', and therefore a very useful alternative to embedding a negation in an 'if' conditional, particularly if the conditional contains multiple operators. And that rationale applies even if followed by else/elsif.

爱本泡沫多脆弱 2024-09-12 23:27:20

也许只是个人意见,但我喜欢使用 except 当 if 条件以 !

Just a personal opinion maybe, but I like to use Unless when the if condition would start with a !

北座城市 2024-09-12 23:27:20

语法 if(!$condition) 等效于 except($condition),并且如果交换条件的 NOT'ing,同样如此。

我个人更喜欢仅使用 IF 语句。为什么?因为要记住的东西比较少。如果您有 100 行代码,其中一半使用 except(),另一半使用 if(),那么与仅使用 if() 语句相比,您需要花费更多时间对其进行调试。

不过,您可能会“掌握”unless 和 if 的窍门,因此在两者之间切换根本不需要时间。但这不仅仅是 if() 与 except() 的问题。不要忘记...

if($condition) {
    #passed-condition code
} else {
    #failed-condition code
}

...相当于...

unless(!$condition) {
    #passed-condition code
} else {
    #failed-condition code
}

但是 if(){...}elsif(){...} 呢?如何将其等效为 except(){...}elsunless(){...} ?逻辑越复杂,在if()和unless()之间切换就越困难。您需要记住和平衡的记忆越少,调试自己的代码就越快。

The syntax if(!$condition) is equivalent to unless($condition), and likewise if you swap the NOT'ing of the condition.

I personally prefer using only IF statements. Why? Because it's less to memorize. If you have 100 lines of code, half of it using unless() and the other half using if(), you'll need to spend more time debugging it than if it was just if() statements.

You may "get" the hang of unless and if, though, so that going between the two takes no time at all. But it's not just about if() versus unless(). Don't forget that...

if($condition) {
    #passed-condition code
} else {
    #failed-condition code
}

...is equivalent to...

unless(!$condition) {
    #passed-condition code
} else {
    #failed-condition code
}

But what about if(){...}elsif(){...}? How would you make an equivalent of that into unless(){...}elsunless(){...}? The more complicated the logic, the more difficult it becomes to go between if() and unless(). The less you have to remember and balance in your memory, the quicker you will be to debug your own code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文