数组的Perl输入

r9f1avp5  于 8个月前  发布在  Perl
关注(0)|答案(2)|浏览(89)

我将输入输入到一个数组中,直到用户按下命令d。我首先执行了一个while循环,但后来切换到了一个for循环,你会在注解中看到。无论是for循环还是while循环,输入都只是每隔一个输入到数组中。所以如果我输入一个b c d e f,然后打印数组,它只输出b d f。为什么会发生这种情况,我如何修复它?

print "Please enter your favorite foods, one per line\n";
#my $i = 0;
for(my $i = 0; $foods = <>; $i++){
  #while($foods = <>){
    chomp($foods = <>);
  push(@foods, ($foods));
#    $foods[$i] = $foods;
#}
}

Please enter your favorite foods, one per line
a
b
c
d
e
f
bdf
ua4mk5z4

ua4mk5z41#

也许是这样的:

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

say 'Please enter your favourite foods, one per line:';

my @food;

while (<>) {
  push @food, $_ if /\S/; # ignore empty input
}

chomp @food;

say join ' / ', @food;
xuo3flqw

xuo3flqw2#

OP代码中的功能问题是FOR循环的设置从终端读取$foods的值,

for(my $i = 0; $foods = <>; $i++)

然后在循环体中我们为它读入一个新值,

chomp($foods = <>)

因此,在循环顶部输入的值在没有使用过的情况下被替换,所以你只是将第二个/第四个/第六个条目推入数组。
如果将最后一个代码片段更改为chomp($foods),您将获得所有六个值。

相关问题