有没有理由在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 whichi
counts up from0
to10
at the same time thatj
is counting down from10
to0
?
So, your instinct that it's mainly useful in for
loops is a good one, I think.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.