Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate for making such a thing work in perl : `for(10...0)`

Tags:

for-loop

perl

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?

like image 749
udiboy1209 Avatar asked Aug 30 '13 18:08

udiboy1209


3 Answers

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.

like image 69
amon Avatar answered Oct 02 '22 02:10

amon


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.

like image 24
mob Avatar answered Oct 02 '22 01:10

mob


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}
like image 33
dlamblin Avatar answered Oct 02 '22 01:10

dlamblin