in reply to Syntax for Hashes of Hashes

Hi,

my %g = (); while(<INFO>) { my ($name,$specie,$gender,$age,$hairColor) = split /,/,$_; $g{$name} = { SPECIE => $specie, GENDER => $gender, AGE => $age, HAIRCOLOR => $hairColor, }; }

To pass the inner hash as a reference to a subroutine you can simply say:

call_sub( $g{$name} );

That's because the value of the hash key is actually a reference to a hash.

But in this case I wouldn't use the $name as the key, because that way you can't have 2 people with the same name... Better to use a unique field, or an id number...

And then other interesting things like OO and DB... ;-)

Regards,

|fire| at irc.freenode.net

I like merlyn's disclaimer

Replies are listed 'Best First'.
Re^2: Syntax for Hashes of Hashes
by o2bwise (Scribe) on Jul 24, 2005 at 19:26 UTC
    Hey Fire,

    Thanks!

    Two questions...

    1. What if you want to create the inner hash without setting any value to it during its creation? How do you "inform" that it is a hash that is being created?

    What is the conditional for seeing if it exists? Is it?

    if !($g{$name})
    Thanks again...

    Tony (o2)
      To define an inner hash without contents, you can do:
      $g{$name} = {};
      to check for existence, you do:
      if ( exists($g{$name} ) { }
      Otherwise, the way you were doing it, you are only checking to see if the value of the key is defined with a true value.

        However be careful with exists(), it creates stuff for you:

        use Data::Dumper; use strict; use warnings; my $h = {}; if (exists($h->{"a"}{"b"})) { } if (exists($h->{"a"})) { print "exists\n"; } print Dumper($h);

        This will make $h->{"a"} exists.

        hubb0r,

        Thanks, man!

        Say, got one more question. I am trying to figure out the syntax for printing out the values of the inner hash OUTSIDE the subroutine.

        Here is as far as I am (I pushed all name values in an array called @names):

        print "From outside the subroutine:\n"; my $i = 0; while ( $i < @names ) { print "$myHash{ $names[$i] }{ name }\n"; $i++; }
        and I have this error:

        Use of uninitialized value in concatenation (.) or string at hashOfHas +hes.pl line 22, <INFO> line 5.
        Line 22 is the print statement within the while loop (figures).

        Thanks again...

        Tony

      As a matter of fact there is no need to for you to create inner hash if you don't need it RIGHT AT THE MOMENT. it will be created at the time you want it. For example:

      use Data::Dumper; use strict; use warnings; my $h = {}; $h->{"a"}{"b"}{"c"} = 1; print Dumper($h);

      This works, and there is no need to create level a first, then level b, then assign level c. Level a and b magically come to existance.