Perl 的标量逗号运算符什么时候有用?

发布于 2024-08-20 15:01:41 字数 42 浏览 7 评论 0原文

除了在 for 循环之外,是否有任何理由在任何地方使用标量逗号运算符?

Is there any reason to use a scalar comma operator anywhere other than in a for loop?

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

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

发布评论

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

评论(2

梦归所梦 2024-08-27 15:01:41

由于 Perl 标量逗号是 C 逗号运算符的“端口”,这些注释 可能是恰当的:

有时候,你会发现自己身处
C 期望的情况
单个表达式,但你有两个
你想说的话。最
常见(实际上是唯一常见)
示例位于 for 循环中,具体来说
第一、第三控制
表达式。如果(例如)你怎么办
想要一个其中 i 计数的循环
同时从 0 上升到 10
j 正在从 10 倒计时到 0

因此,我认为您的直觉认为它主要在 for 循环中有用,这是一个很好的直觉。

Since the Perl scalar comma is a "port" of the C comma operator, these comments are probably apropos:

Once in a while, you find yourself in
a situation in which C expects a
single expression, but you have two
things you want to say. The most
common (and in fact the only common)
example is in a for loop, specifically
the first and third controlling
expressions. What if (for example) you
want to have a loop in which i counts
up from 0 to 10 at the same time that
j is counting down from 10 to 0?

So, your instinct that it's mainly useful in for loops is a good one, I think.

物价感观 2024-08-27 15:01:41

我偶尔会在条件(有时错误地称为“三元”)运算符中使用它,如果代码比将其分解为真正的 if/else 更容易阅读:

my $blah = condition() ? do_this(), do_that() : do_the_other_thing();

它也可以在最后结果很重要的某些表达式中使用,例如在 grep 表达式中,但在这种情况下,它与使用分号相同:

my @results = grep { setup(), condition() } @list;

I occasionally use it in the conditional (sometimes erroneously called "the ternary") operator, if the code is easier to read than breaking it out into a real if/else:

my $blah = condition() ? do_this(), do_that() : do_the_other_thing();

It could also be used in some expression where the last result is important, such as in a grep expression, but in this case it's just the same as if a semicolon was used:

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