答案可能就在我面前......但是我已经把太多的头发拉到了这个上面。我有一个脚本,它读入名字和姓氏列表,将它们存储在数组中,然后随机选择10个名字和姓氏进行打印。例如,它将打印“John Doe”。抓住名字和姓氏之后。我有一切正常,但程序不是在同一行上打印它们。它会自动创建一个新行,如下所示:
John
Doe
这是脚本:
use strict;
#Open boy names
my $boyFile = "boyFirst.txt";
open (FH, "< $boyFile") or die "Can not open $boyFile for read: $!";
my @allNames;
while (<FH>) # While file is open, keep putting new lines into list
{
push (@allNames, $_);
}
close FH or die "Can not close $boyFile: $!";
#open girl names
my $girlFile = "girlFirst.txt";
open (FH, "< $girlFile") or die "Can not open $girlFile for read: $!";
#my @girlLines;
while (<FH>)
{
push (@allNames, $_); # While file is open, keep putting new lines into list
}
close FH or die "Can not close $girlFile: $!";
#open last names
my $lastFile = "lastName.txt";
open (FH, "< $lastFile") or die "Can not open $lastFile for read: $!";
my @lastLines;
while (<FH>)
{
push (@lastLines, $_); # While file is open, keep putting new lines into list
}
close FH or die "Can not close $lastFile: $!";
#Generate Alphabet
my @alpha = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
my $name;
my $lastName;
my $randomFirstName;
my $randomLastName;
for (1 .. 10)
{
$name = rand @allNames;
$lastName = rand @lastLines;
$randomFirstName = $allNames[$name];
$randomLastName = $lastLines[$lastName];
printf("$randomFirstName");
printf("$randomLastName");
}
提示和建议也很感激。脚本新手:)
答案 0 :(得分:4)
在所有chomp;
语句之前添加push
。在将{#1}}推送到数组之前,它将删除行结束字符。然后在最终$_
语句后添加print "\n";
。