这在perl中不起作用:for(10 .. 0)它根本不会循环一次,因为它最初会检查10>0。创建递减迭代for循环有什么替代方法吗?
for(10 .. 0)
10>0
for
6yoyoihd1#
for (reverse 0 .. 10) { say $_;}
for (reverse 0 .. 10) {
say $_;
}
使用reverse function。不幸的是,这会强制对列表中的范围求值,因此这比没有reverse的循环使用更多的内存。
reverse
u3r8eeie2#
我不确定简洁是否是这样做的一个很好的标准,但在反相解决方案中不需要map,在反转解决方案中也不需要reverse:
map
# 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 Alternativesfor(@_=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 reversefor(reverse 0..10){say}
# 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}
yqyhoc1h3#
for (map -$_,-10..0) { ... }for (map 10-$_,0..10) { ... }
for (map -$_,-10..0) { ... }
for (map 10-$_,0..10) { ... }
如果范围的任何部分为负,则第一个部分比使用reverse短。
3条答案
按热度按时间6yoyoihd1#
使用
reverse
function。不幸的是,这会强制对列表中的范围求值,因此这比没有
reverse
的循环使用更多的内存。u3r8eeie2#
我不确定简洁是否是这样做的一个很好的标准,但在反相解决方案中不需要
map
,在反转解决方案中也不需要reverse
:yqyhoc1h3#
如果范围的任何部分为负,则第一个部分比使用
reverse
短。