将输入中的字母拆分为perl

时间:2018-04-23 23:08:55

标签: arrays perl data-dumper

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

#!/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

如果他们的输入是“house”

,我的输出应该看起来像这样
@userarray[0]= "h"
@userarray[1]= "o"
@userarray[2]= "u"
@userarray[3]= "s"
@userarray[4]= "e"

但是,当我输入内容时,只需打印一个空白屏幕,尽管有严格的警告并且没有任何回复。我哪里出错了?

2 个答案:

答案 0 :(得分: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()删除记录末尾(行)的尾随记录分隔符(换行符号)。如果你想保留它们,请不要使用它。我以为你不是。

答案 1 :(得分:1)

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

print "Input?";
while (my $userinput = <STDIN>) {
  chomp $userinput; # remove trailing newline
  my @userarray = split //, $userinput; 
  print Dumper(\@userarray);
}