0
答えはおそらく私の目の前にありますが、私はあまりにも多くの髪の毛を引っ張ってきました。私は、名字と姓のリストを読み込み、配列に格納した後、ランダムに10姓と名字を選んで印刷するスクリプトを持っています。たとえば、 "John Doe"と印刷されます。最初と最後の名前をつかんだ後。私はすべてが機能しているが、プログラムは同じ行にそれらを印刷していない。それはautomaticllyにこのように、新しい行を作っている:ここでPerl:配列からランダムに選択された2つの変数を同じ行に印刷する
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");
}
ヒント、およびアドバイスも高く評価されています。スクリプトを初めてご利用の方:
入力を[chomp](http://p3rl.org/chomp)する必要があります。 – choroba
ところで、 'my @alpha = 'A' .. 'Z';はちょっと短いです。 – choroba
また、$ name、$ lastNameなどはループの外側には必要ないので、不必要に広い範囲で宣言しないでください。 – choroba