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

I am trying to create a hash of arrays.
%listSample = (); - I have tried many variations on the declaration.
This is declared at the top of the file.

when I try to use it like:
push @{ $listSample{Bank} }, 1, 2;

I get a compiler error "Not an array reference."
But only if it is inside the block of a while loop or if statement. Outside the block it works fine. Why is the scope not global?

Replies are listed 'Best First'.
Re: Scope of Hash of arrays.
by tcf22 (Priest) on Sep 18, 2003 at 19:36 UTC
    Can you post some of the surrounding code.
    I can't reproduce the error except for doing this, and doubt this is what you are doing
    my %hash; $hash{test} = {}; push @{$hash{test}}, 1, 2; use Data::Dumper; print Dumper \%hash;
    I've tried various things like
    my %hash; #Tried these things #$hash{test} = 'test'; #$hash{test} = 1; push @{$hash{test}}, 1, 2; use Data::Dumper; print Dumper \%hash;
    They all didn't have the desired result(some didn't push), but they didn't throw that error. This is on Win32 Perl 5.6.

    - Tom

Re: Scope of Hash of arrays.
by zby (Vicar) on Sep 18, 2003 at 18:26 UTC
    zby@moria:~$ perl -e 'push @{ $listSample{Bank} }, 1,2' zby@moria:~$ perl -we 'push @{ $listSample{Bank} }, 1,2' Name "main::listSample" used only once: possible typo at -e line 1. zby@moria:~$ perl -we 'if(1){push @{ $listSample{Bank} }, 1,2}' Name "main::listSample" used only once: possible typo at -e line 1. zby@moria:~$ perl -e 'if(1){push @{ $listSample{Bank} }, 1,2}' zby@moria:~$
    For me it works inside and outside a block. It was perl 5.6.1
Re: Scope of Hash of arrays.
by davido (Cardinal) on Sep 18, 2003 at 18:39 UTC
    If you're trying to build up the array with pushes, maybe try this:

    push @$hash{'Element'}, (1, 2, 3, 4, 5);

    The paranthesis are redundant, and are just there to make the list visually obvious.

    If you're adding one item at a time inside a loop it might look more like this.

    push @$hash{'Element'}, $item;

    Or if you've got another array you're adding you could do it this way:

    push @$hash{'Element'}, @array;

    If you're building the array up in one step you could do it this way, and additional elements could still be pushed onto it later:

    $hash{'Element'} = [1, 2, 3, 4, 5];

    I would have to see a snippet of five or ten lines of code that exhibits the misbehavior you're describing before I could comment on what's wrong. Post a small segment of code that shows the problem and maybe we can help figure it out. FWIW, there isn't anything special about a hash of arrays that would make scoping different for that entity than for some other entity.

    Dave

    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein