in reply to creating defined references to arrays of size zero

Like Ovid said:

my %stacks = ( A => [], B => [], . . . Z => [], ); # microseconds later... my $current_stack = $stacks{ K }; # for example push @$current_stack, 'whatever'; # etc.;
As long as you deal with references (like $current_stack) above, the changes you make will be reflected in the stacks stored in %stacks.

You can initialize the stacks more succinctly with something like this:

my %stacks; @stacks{ @names } = map [], @names;
...where @names holds the names of the stacks.

the lowliest monk

Replies are listed 'Best First'.
Re^2: creating defined references to arrays of size zero
by spieper (Initiate) on Jul 14, 2005 at 07:53 UTC
    strange-- I was doing that. I tried to recreate the code on my home computer and it worked as you all said (and as I originally expected it to). I'm guessing either

    a) my work has a weird version of perl
    b) the larger code I'm working on has some strange options set

    Thanks for all your help.

      aha-- woke up and realized what I was doing-- definitely an ID 10-T error. Most of my keys were one letter, but one was actually a full word (I know the possible keys ahead of time), so I did something stupid like
      hash = { a=>[]; b=>[] c=>[] . . . } #some time later my $key = "alpha" my $array = $hash->{$key};

      At this point there isn't anything at $hash->{$key}, so $array isn't pointing to anything real. When I push onto $array, that memory will get allocated happily, and won't create anything in the hash (which is a very good thing). If instead, the first thing I do is to shove something into @{$hash->{$key}}, a new entry gets magically allocated, and then everything works as expected.

      Obviously I'm not one with the perl yet.

        This is precisely where tlm's suggestion(++) comes in handy:
        You could do:
        my $array = $hash->{$key} ||=[];
        This would initialize the hash value to an empty array ref, when necessary.

             "Income tax returns are the most imaginative fiction being written today." -- Herman Wouk