これらの2行は、dict.txtファイルを書き込み用に開き、次にそれを読み取ろうとします。
open FILE, ">dict.txt" or die $!;
my @words = <FILE>;
書き込み専用ファイルからの読み取りはできないため、失敗します。ファイルが書き込み可能だった場合、それは今空です - あなたの素敵な単語リストを残念。提案:また、「もし」または「は」と開き括弧の間にスペースを入れ
sub go
{
print "Number of lines:";
my $lines = <>;
print "Max words per line:";
my $range = <>;
for (my $i = 0; $i<$lines; $i++){
my $wordcount = int(rand($range));
for (my $s = 0; $s<$wordcount; $s++){
my $range2 = 23496;
my $word = int(rand($range2));
my $chosen = @words[$word];
print "$chosen ";
if ($s=$wordcount){
print "\n";
}
}
}
}
:
open my $file, "<", "dict.txt" or die "$!";
my @words = <$file>;
close $file;
また、のような、オーソドックスな方法であなたのかっこをインデントすることを学ぶしてください。
あなたの割り当てif ($s = $wordcount)
はおそらくあなたが意図したものではありません。ただし、条件のループのスコープ内にあるため、条件if ($s == $wordcount)
は常にfalseになります。ロジックのその部分を再考する必要があります。
平均では、あなたの関数には、より良い名前をgo
よりも選択する必要があります。また、go();
と呼び出すほうがよいでしょう。あなたが投稿する前にこのようなエラーを修正する必要があり
Scalar value @words[$word] better written as $words[$word] at xx.pl line 19.
:私はあなたのスクリプトをコンパイルテストする場合について
は、Perlは警告しています。
あなたが持っている:
my $range2 = 23496;
my $word = int(rand($range2));
あなたの辞書以上23496個の単語を持っていない限り、あなたはおそらく初期化されていない単語にアクセスします。あなたはおそらく使用する必要があります:
my $range2 = scalar(@words);
それは解決するいくつかの論理的な問題を残します。
含む
word1
word2
word3
word4
nibelung
abyssinia
tirade
pearl
そして 'xx.pl':
#!/usr/bin/env perl
use strict;
use warnings;
open my $file, "<", "dict.txt" or die $!;
my @words = <$file>;
close $file;
sub go
{
print "Number of lines: ";
my $lines = <>;
print "Max words per line: ";
my $range = <>;
my $range2 = scalar(@words);
for (1..$lines)
{
for (1..$range)
{
my $index = int(rand($range2));
my $chosen = $words[$index];
chomp $chosen;
print "$chosen ";
}
print "\n";
}
}
go();
を、私はそれを実行すると、私が手:
$ perl xx.pl
Number of lines: 3
Max words per line: 4
word4 word3 word4 nibelung
abyssinia pearl word1 tirade
word3 word1 word3 word2
$
を含む 'dict.txt' が指定
なぜ「FILE」から読もうとしていますか? 'open'の呼び出しで'> 'を使うと、書き込み専用のハンドルが開きます。 –
スクリプトで何をしたいのか簡単に説明できますか? –
ああええ。私は単に辞書ファイルを配列に読み込み、その配列から無作為に単語を選んで、行と近似行の長さがユーザーによって指定されていればその単語を段落に出力しようとしています。 ------------ そして、私は "<"を使用するべきですか?私はオープンしていたので(FILE、 "dict.txt")、まだ動作していません。 --------- 正確なエラーは、「連結(。)の@words内の初期化されていない値の使用、またはpoemgen.pl 19行目、<>行2の 」の文字列です。 – danem