This doesn't work in perl : for(10...0)
It essentially doesn't loop even once, because it checks that 10>0
initially.
Any alternate shorthand for creating a decreasing iterating for
loop?
for (reverse 0 .. 10) {
say $_;
}
Use the reverse
function.
Unfortunately, this forces evaluation of the range to a list, so this uses more memory than the loop without reverse
.
for (map -$_,-10..0) { ... }
for (map 10-$_,0..10) { ... }
If any part of the range is negative, then the first one is shorter than using reverse
.
I'm not sure brevity is a great criteria for doing this, but you don't need the map
in the inverting solution, nor reverse
in the reversing one:
# By Inverting without map, one of:
for(-10..0){$_=-$_;say}
for(-10..0){$_*=-1;say}
# Compare to similar length with map:
for(map-$_,-10..0){say}
# Can just use -$_ where $_ is used, if $_ is used < 6 times; that's shorter.
for(-10..0){say-$_}
# By Reversing without reverse (in a sub; in main use @ARGV or @l=...=pop@l)
@_=0..10;while($_=pop){say}
# More Pop Alternatives
for(@_=0..10;$_=pop;say){}
@_=0..10;for(;$_=pop;){say}
@_=0..10;do{say$_=pop}while$_
($_,@_)=(10,0..9);do{say}while($_=pop)
# Though, yeah, it's shorter with reverse
for(reverse 0..10){say}
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