0

The following code gives the error: Global symbol "$ground" requires explicit package name at main.pl line 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){
            push@{$ground[$x]},"-";
        }
    }
}

&map_gen;
foreach my $y(0..scalar@{$ground}){
    foreach my $x(0..scalar@{$ground[$y]}){
        print $ground[$x][$y];
    }
    print"\n";
}

I have researched this error and it is due to referencing an undeclared variable, but I declared @ground before the error appears. I suspect it's because its a scalar reference, but dont know how to correct it.

Calvin Koder
  • 953
  • 2
  • 7
  • 12
  • 3
    side note; prefer `map_gen();` over `&map_gen;` => http://stackoverflow.com/questions/8912049/difference-between-function-and-function-in-perl – mpapec Nov 22 '13 at 18:25
  • @mpapec: Put hyperlinks into comments using `[text](http://...)` – Borodin Nov 22 '13 at 21:22

1 Answers1

3

You declared @ground, but you use $ground in the following line:

foreach my $y(0..scalar@{$ground}){

The solution isn't to declare $ground (as it would never have a value), but to use the correct variable

foreach my $y(0..scalar@ground){

But that loops once too many. You want

foreach my $y(0..$#ground){
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Now it says syntax error at main.pl line 20, near "$#ground[" and syntax error at main.pl line 24 near "}" here is the code: 'foreach my $y(0..$#ground){ foreach my $x(0..$#ground[$y]){ print $ground[$x][$y]; } }' – Calvin Koder Nov 22 '13 at 18:24
  • 1
    That's not the code that's giving the error. Apparently, you used `$#ground[` somewhere. (Note the trailing `[`.) Probably trying to fix the off-by-one error on the next line. You should be using `$#{$ground[$y]}` – ikegami Nov 22 '13 at 18:29