bryan172 has asked for the wisdom of the Perl Monks concerning the following question:

All I'm trying to do is use a sub to print out a nested set of arrays. It should be simple, but I can't figure out what I'm doing wrong. The foreach loop works outside of the sub, but not inside the sub, which is odd because the array should be within the scope of the sub. Here's the code:
#!c:\strawberry\perl\bin\perl.exe -w displayBoard( ); @test = ( [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], ); sub displayBoard { foreach ( @test ) { print "@$_\n"; } }
I would be very grateful if someone would point out the obvious thing I'm not seeing. Thanks! Bryan

Replies are listed 'Best First'.
Re: I can't figure out what's wrong with this foreach loop
by toolic (Bishop) on Mar 13, 2011 at 18:45 UTC
    Call your function after you initialize the array:
    @test = ( [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], ); displayBoard( );
Re: I can't figure out what's wrong with this foreach loop
by wind (Priest) on Mar 13, 2011 at 20:24 UTC

    The two main issues have already been stated, not defined yet and use strict.

    However, I'd also add that you avoid using global and instead pass parameters to your functions. If you did that, it would be much more obvious that a data structure is not defined yet when you make our function call.

    #!c:\strawberry\perl\bin\perl.exe -w use strict; my @test = ( [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], ); displayBoard(@test); sub displayBoard { foreach ( @_ ) { print "@$_\n"; } }
pragmas are good
by am0c (Initiate) on Mar 13, 2011 at 19:11 UTC
    And this is why you should use 'strict' and 'warnings' pragma in practice. You would have found the bug earlier if you had had these pragmas turned on. As you would have seen a warning saying 'undefined variable is being used.'
      He does have warnings turned on, and his code doesn't issue that warning. @test is an array; it cannot be undefined.
        Yep, that did it. I knew it was something silly. I'll make sure to turn on strict from now on, too. Thanks again! Bryan