Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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?

like image 632
Flimm Avatar asked Oct 22 '14 10:10

Flimm


2 Answers

Non pretty solution,

for (my $i=1_000_000; $i >= 1; $i--) {

   print "$i\n";
}
like image 166
mpapec Avatar answered Sep 17 '22 18:09

mpapec


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--;
}
like image 37
TLP Avatar answered Sep 20 '22 18:09

TLP