0

我正在做一个项目,我需要从用户那里获取输入,然后将其切割成单独的字符以供以后使用(将它们向上移动一个字符),但是我无法将输入输入到数组和将其打印出来以检查其是否在其中。目前我的代码是

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $count=0;      # this block just creates variables
my $userinput;

print "Input?";      
$userinput=<STDIN>;   # this block just gets input and creates the array
my @userarray=();

while(<@userarray>) {
@userarray = split('', $userinput);   #this block should loop as many times as there are characters in the input while separating the characters
}

print Dumper(@userarray);   #this should print the array

如果他们的输入是“房子”,我的输出应该看起来像这样

@userarray[0]= "h"
@userarray[1]= "o"
@userarray[2]= "u"
@userarray[3]= "s"
@userarray[4]= "e"

但是,当我确实在其中输入某些内容时,尽管有严格的警告并且没有返回任何内容,但它只是打印出一个空白屏幕。我哪里做错了?

4

2 回答 2

4

<D>从标量上下文中的文件句柄中读取并返回一个(下一个)记录(如果记录分隔符$/未更改,则为一行)。D在列表上下文中,返回所有剩余记录(作为数组)。

说了这么多,这部分的问题是:

$userinput=<STDIN>;   # this block just gets input and creates the array
my @userarray=();

while(<@userarray>) {
@userarray = split('', $userinput);   #this block should loop as many times as there are characters in the input while separating the characters
}

<@userarray>@userarray确定不是有效的文件句柄,不返回任何内容。所以这个循环永远不会进入。

如果您希望用户只输入一行,则根本不要使用循环。读取一行并将其拆分。

$userinput=<STDIN>;   # this block just gets input and creates the array
chomp($userinput);
my @userarray=();

@userarray = split('', $userinput);

但是该循环可能表明,您希望用户能够输入多行。如果是这样,循环直到没有输入(EOF),逐行读取输入。拆分行并将结果推送到您的数组中。

while(my $line = <STDIN>) {
  chomp($line);
  push(@userarray, split('', $line));
  print(join(',', @userarray) . "\n");
}

对于两种方式:chomp()删除记录(行)末尾的尾随记录分隔符(新行)。如果您想保留这些,请不要使用它。我以为你没有。

于 2018-04-23T23:48:44.307 回答
1

这是一种常见的 Perl 模式。您想要循环以便用户可以输入更多数据。尝试这样的事情:

print "Input?";
while (my $userinput = <STDIN>) {
  chomp $userinput; # remove trailing newline
  my @userarray = split //, $userinput; 
  print Dumper(\@userarray);
}
于 2018-04-23T23:33:42.390 回答