gpt4 book ai didi

perl - 为什么这个简单的 Perl push/pop 程序不工作?

转载 作者:行者123 更新时间:2023-12-04 10:13:20 26 4
gpt4 key购买 nike

我正在阅读 Llama ( Learning Perl ) 书,并正在做练习。对于这个练习:

Write a program that reads a list of strings on separate lines until end-of-input and prints out the list in reverse order. [. . .]



嗯,我已经想出了一个更简单的方法(我记得你可以在数组上使用 reverse...Perl 太棒了...到目前为止),但我想知道为什么这个方法不起作用。
#!/usr/bin/perl

use 5.010;

chomp(@strings = <STDIN>);

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

while($i++ <= scalar @revstrings){
say pop @revstrings;
}

它是这样的:

$ ./first
one
two
three

[^D]
three
two
$



如果我更改 <=,输出是相同的在while循环中只是 < .

最佳答案

你永远不会半途而废......每次通过最后一次迭代,你都会得到:

  • $i++意味着 $i将增加一;
  • pop @revstrings将意味着 scalar @revstrings将减少一。

  • 他们会在中间相遇,当 $i++刚刚超过原来的一半 @revstrings长度。

    实际上, $i++没有必要,因为 scalar @revstrings当数组为空时将为零,因此您只需要:
    while(scalar @revstrings){
    say pop @revstrings;
    }

    关于perl - 为什么这个简单的 Perl push/pop 程序不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1081476/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com