Range operator decrementing from largest to smallest: 10..1 [duplicate]

元气小坏坏 提交于 2020-07-03 06:37:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!