范围运算符从最大到最小递减:10..1 [英] Range operator decrementing from largest to smallest: 10..1

查看:51
本文介绍了范围运算符从最大到最小递减:10..1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl 有一个范围运算符,当在 foreach 循环中使用时,不会创建临时数组:

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
}

我可以使用内置的 reverse,但这会保持不创建临时数组的优化吗?

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?

推荐答案

可以只用比范围顶部多一的数字减去你得到的数字:

You could just subtract the number you've got from one more than the top of the range:

foreach (1 .. 1_000_000) {
    my $n = 1_000_001 - $_;
    ...
}

for (-1_000_000 .. -1) {
    my $n = -$_;
    ...
}

这篇关于范围运算符从最大到最小递减:10..1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆