我一直在学习Perl,每当我编写一个非平凡的脚本时,我总会收到此错误消息。我一直认为我对它有很好的理解,但我想我没有。这是一个草率马尔可夫链示例(未经测试),其中包含以下错误。
#!/usr/bin/perl -w
use strict;
sub croak { die "$0: @_: $!\n"; }
sub output {
my %chains = shift;
my @keys = keys %chains;
my $index = rand($keys);
my $key = $keys[$index];
my $out_buf = $key;
for (my $i = 0; $i < 100; ++$i) {
my $aref = $chains{$key};
my $word = @$aref[rand($aref)];
$out_buf .= " $word";
$key =~ s/.+ //;
$key .= " $word";
}
print $out_buf, "\n";
}
sub get_chains {
my %chains;
my @prefixes
while (my $line = <FILE>) {
my @words = split " ", $line;
foreach my $word (@words) {
if ($prefixes == 2) {
my $key = join " ", @prefixes;
my $arr_ref = $chains{$key};
push(@$arr_ref, $word);
shift @prefixes;
}
push(@prefixes, $word);
}
}
return %chains;
}
sub load_book {
my $path_name = shift @ARGV;
open(FILE, $path_name) || croak "File not found.\n";
}
load_book;
my %chains = get_chains;
output %chains;
----ERRORS----
"my" variable $line masks earlier declaration in same statement at markov.pl line 33.
"my" variable $path_name masks earlier declaration in same scope at markov.pl line 55.
Global symbol "$keys" requires explicit package name at markov.pl line 12.
syntax error at markov.pl line 32, near ") {"
Global symbol "$prefixes" requires explicit package name at markov.pl line 36.
Global symbol "%chains" requires explicit package name at markov.pl line 48.
syntax error at markov.pl line 49, near "}"
syntax error at markov.pl line 56, near "}"
Execution of markov.pl aborted due to compilation errors.
我犯了什么错误?
答案 0 :(得分:15)
您的脚本中有三个语法错误:
全局符号“$ keys”需要在markov.pl第12行显式包名。
您没有声明$ keys,并且由于“use strict”,这是一个致命的错误。 你可能意味着:
my $index = rand(@keys);
第二个错误:
全局符号“$ prefixes”需要在markov.pl第36行显式包名。
是一回事:你的意思是:
if (@prefixes == 2) {
最后,在第30行中,您错过了分号:
my @prefixes
这会使解析器混淆,并导致所有其他错误和警告。
如果您不清楚使用符号($,@,%),则可能需要阅读perldata文档。