加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:53:35 所属栏目:大数据 来源:网络整理
导读:我正在阅读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. [. . .] 好吧,我已经想出了一个更简单的方法(我记得
我正在阅读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. [. . .]

好吧,我已经想出了一个更简单的方法(我记得你可以在数组上使用反向… 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将增加1;
> pop @revstrings意味着标量@revstrings将减少一个.

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

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

while(scalar @revstrings){
    say pop @revstrings;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读