2010-08-28 29 views
2

我一直在學習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. 

什麼錯誤(S)我在做什麼?

回答

15

有在你的腳本3個語法錯誤:

全局符號「$鍵」需要在markov.pl行明確包名12

你沒有申報$鑰匙,因爲「嚴格使用」,這是一個致命的錯誤。 你大概的意思是:

my $index = rand(@keys); 

第二個錯誤:

全局符號 「$前綴」 需要在markov.pl線36

是一回事明確軟件包名稱:你的意思:

if (@prefixes == 2) { 

最後,在第30行,你錯過了一個分號後:

my @prefixes 

這使混淆解析器,並導致所有其他錯誤和警告。

如果您不清楚使用sigils($,@,%),您可能需要閱讀perldata文檔。

+0

我以爲$鍵會在標量上下文中被解釋,即列表中元素的數量。我現在明白了。謝謝。 – floogads 2010-08-28 23:22:47

+0

雖然其他部分仍然存在問題。例如,如何在load_book中掩蓋$ path_name? – floogads 2010-08-28 23:39:54

+0

編輯:語法錯誤導致其他錯誤。 – floogads 2010-08-28 23:45:38

相關問題