2013-11-22 28 views
0

下面的代碼提供了錯誤:全局符號「$地」需要在main.pl線19

#!/usr/local/bin/perl 
use strict; 
use warnings; 

my @ground=(); 

sub map_gen{ 
    my $width=10; 
    my $height=10; 

    foreach my $x(0..$width){ 
     foreach my $y(0..$height){ 
      [email protected]{$ground[$x]},"-"; 
     } 
    } 
} 

&map_gen; 
foreach my $y([email protected]{$ground}){ 
    foreach my $x([email protected]{$ground[$y]}){ 
     print $ground[$x][$y]; 
    } 
    print"\n"; 
} 

我研究這個錯誤,明確包名這是由於引用了一個未聲明的變量,但是我在錯誤出現之前聲明瞭@ground。我懷疑這是因爲它是一個標量引用,但不知道如何糾正它。

+3

旁註;喜歡'map_gen();'over'&map_gen;'=> http://stackoverflow.com/questions/8912049/difference-between-function-and-function-in-perl –

+0

@mpapec:把超鏈接放入評論使用'文本](http:// ...)' – Borodin

回答

3

你宣佈@ground,但你在下面一行用$ground

foreach my $y([email protected]{$ground}){ 

該解決方案是不是要宣佈$ground(因爲它永遠不會有一個值),而是利用正確的變量

foreach my $y([email protected]){ 

但是,這種循環太多。你想要

foreach my $y(0..$#ground){ 
+0

現在它說main.pl行20附近的語法錯誤,「$#ground [」和main.pl行24附近的語法錯誤「}」 這裏是代碼: 'foreach my $ y(0.. $#ground){ foreach my $ x(0.. $#ground [$ y]){ print $ ground [$ x] [$ y]; } }' –

+1

這不是給出錯誤的代碼。顯然,你在某處使用了'$#ground [']。 (注意後面的'['。)可能試圖修復下一行的錯誤。你應該使用'$#{$ ground [$ y]}' – ikegami

+1

http://www.perlmonks.org/?node_id=977408 – ikegami

相關問題