2013-11-22 30 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

相关问题