问题
Perl has a range operator, which when used in a foreach loop, does not create a temporary array:
foreach (1 .. 1_000_000) {
# code
}
If the first integer is smaller than the second integer, then no iterations are run:
foreach (1_000_000 .. 1) {
# code here never runs
}
I could use the reverse built-in, but would this keep the optimisation of not creating a temporary array?
foreach (reverse 1 .. 1_000_000) {
# code
}
Is there a way that's as pretty and fast as the range operator for decreasing numbers, rather than increasing ones?
回答1:
Non pretty solution,
for (my $i=1_000_000; $i >= 1; $i--) {
print "$i\n";
}
回答2:
While for is nice, while might be better suited.
my $n = 1_000_000;
while ($n >= 1) {
...
} continue { # continue block will always be called, even if next is used
$n--;
}
回答3:
You could just subtract the number you've got from one more than the top of the range:
foreach (1 .. 1_000_000) {
my $n = 1_000_001 - $_;
...
}
and
for (-1_000_000 .. -1) {
my $n = -$_;
...
}
来源:https://stackoverflow.com/questions/26505835/range-operator-decrementing-from-largest-to-smallest-10-1