Chon-Ji has asked for the wisdom of the Perl Monks concerning the following question:

%List = (); #some initialization for each $element($List{$key1}{$key2}{$key3}{$key4}{$key5}) #do something... end
Could someone please explain how this hash list works? I mean, I know keys could be used to access certain elements in a hash, but hy so many keys involved in a single hash list? thanks

Replies are listed 'Best First'.
Re: Hash quesiton
by Zaxo (Archbishop) on Jun 13, 2006 at 05:56 UTC

    I think we need to see more, there are some ambiguous things there. for each is wrong one way or another, but I can't tell which. It might be meant as foreach, or it might lack parens, intending the less likely for (each  . . .). Or do you mean for our $element ($List{.....}) ?

    What is $element? As written, it makes a syntax error with the parens. If it's a code reference, you need to deref with -> before the parens. That would give trouble with each, since it expects a hash and the closest things a sub can return is a list of key/value pairs or a hash reference.

    Your hash structure itself is just a HoHoHo...H which has some kind of scalar data five levels down.

    All told, there are too many errors there to tell what's intended.

    After Compline,
    Zaxo

Re: Hash quesiton
by Joost (Canon) on Jun 13, 2006 at 09:13 UTC
    Well, first of all, that code DOESN'T work.

    %List isn't a list but a hash which contains as it's value for $key1 a reference to an anonymous hash which contains as it's value for $key2 a reference to an anonymous hash which contains as it's value for $key3 a reference to an anonymous hash... well you get the picture.

    However, since hash values are always scalars, the for each statement is wrong here (each is normally not used like that anyway). Either the last value is an array reference, in which case you need to dereference it:

    for my $element (@{$List{$key1}{$key2}{$key3}{$key4}{$key5}}) { .. }
    or it's a hash reference:
    while (my $name,$value) = each %{$List{$key1}{$key2}{$key3}{$key4}{$ke +y5}}) { .. }
    or it's a simple scalar:
    my $value = $List{$key1}{$key2}{$key3}{$key4}{$key5}}

    see perlreftut and perlref.