为什么这个简单的Perl推/弹程序不起作用?

Car*_*ers 7 perl

我正在阅读Llama(Learning Perl)一书,并正在进行练习.对于这个练习:

编写一个程序,在单独的行上读取字符串列表,直到输入结束,并以相反的顺序打印出列表.[ .]

好吧,我已经想出了一个更简单的方法(我记得你可以reverse在数组上使用......到目前为止,Perl是如此......真棒),但我想知道为什么这个没有用.

#!/usr/bin/perl

use 5.010;

chomp(@strings = <STDIN>);

foreach (@strings){
    push @revstrings, $_;
}

while($i++ <= scalar @revstrings){
    say pop @revstrings;
}
Run Code Online (Sandbox Code Playgroud)

它是这样的:

$ ./first
one
two
three

[^ D]
三个
两个
$

如果我<=将while循环更改为just,则输出相同<.

Sto*_*bor 15

你永远不会过中...每次通过最后一次迭代,你会得到:

  • $i++意味着$i会增加一个;
  • pop @revstrings意味着scalar @revstrings会减少一个.

当它们$i++超过原始@revstrings长度的一半时,它们会在中间相遇.

实际上,这$i++是不必要的,因为scalar @revstrings当数组为空时将为零,所以你只需要:

while(scalar @revstrings){
    say pop @revstrings;
}
Run Code Online (Sandbox Code Playgroud)

  • 也不需要'标量'.while评估boolean(标量)上下文中的条件.所以虽然(@revstrings){...}会做到这一点. (10认同)