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?
Non pretty solution,
for (my $i=1_000_000; $i >= 1; $i--) {
print "$i\n";
}
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--;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With