在perl中实现这样一个功能的替代方法:对于(10..0)

lymgl2op  于 2022-11-15  发布在  Perl
关注(0)|答案(3)|浏览(143)

这在perl中不起作用:for(10 .. 0)它根本不会循环一次,因为它最初会检查10>0
创建递减迭代for循环有什么替代方法吗?

6yoyoihd

6yoyoihd1#

  1. for (reverse 0 .. 10) {
  2. say $_;
  3. }

使用reverse function
不幸的是,这会强制对列表中的范围求值,因此这比没有reverse的循环使用更多的内存。

u3r8eeie

u3r8eeie2#

我不确定简洁是否是这样做的一个很好的标准,但在反相解决方案中不需要map,在反转解决方案中也不需要reverse

  1. # By Inverting without map, one of:
  2. for(-10..0){$_=-$_;say}
  3. for(-10..0){$_*=-1;say}
  4. # Compare to similar length with map:
  5. for(map-$_,-10..0){say}
  6. # Can just use -$_ where $_ is used, if $_ is used < 6 times; that's shorter.
  7. for(-10..0){say-$_}
  8. # By Reversing without reverse (in a sub; in main use @ARGV or @l=...=pop@l)
  9. @_=0..10;while($_=pop){say}
  10. # More Pop Alternatives
  11. for(@_=0..10;$_=pop;say){}
  12. @_=0..10;for(;$_=pop;){say}
  13. @_=0..10;do{say$_=pop}while$_
  14. ($_,@_)=(10,0..9);do{say}while($_=pop)
  15. # Though, yeah, it's shorter with reverse
  16. for(reverse 0..10){say}
展开查看全部
yqyhoc1h

yqyhoc1h3#

  1. for (map -$_,-10..0) { ... }
  2. for (map 10-$_,0..10) { ... }

如果范围的任何部分为负,则第一个部分比使用reverse短。

相关问题