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

I'm trying to print out the values of "status" and "id". I have the following structure, as printed by Dumper:
$VAR1 = { 'Room2' => { 'tag' => '10', 'status' => 'active', 'id' => '1234' }, ...
I'm able to print out the room names, but can't figure how to get the status or id. this is my code:
foreach my $room ( keys %{$ret} ) { print $room; print {$room}{id}; #doesn't work foreach my $id (keys %{$ret{$room}}){ print $id; #nothing print {$ret}{$room}->{$id} ; } print "\n"; }
Any pointers greatfully accpeted!

Replies are listed 'Best First'.
Re: hash of hashes
by Loops (Curate) on Apr 18, 2013 at 03:00 UTC
    Hi there,

    In your "foreach" loops, you're traversing a list of keys within the hashes and getting back just the value of those keys. Not a reference you can use directly to access the hash. To turn this into such a reference you can do like so:

    my $inner = $ret->{$room};

    That is, you lookup the value held in the outer hash, using the key that you're currently looping over. A complete program might look like this:

    use strict; use warnings; use feature 'say'; my $ret = { room1 => { tag => 5, status => 'lazy', id => 5823 } +, room2 => { tag => 10, status => 'active', id => 1234 } +, }; for my $room ( sort keys $ret ) { say $room; my $inner = $ret->{$room}; say "\t$_ => $inner->{$_}" for sort keys $inner; }
      I was surprised to see that you could get "keys" for a scalar.

      Then I RTFM, and found:

      Starting with Perl 5.14, "keys" can take a scalar EXPR, which must contain a reference to an unblessed hash or array. The argument will be dereferenced automatically. This aspect of "keys" is considered highly experimental. The exact behaviour may change in a future version of Perl.
      So - I would continue to code your last line as:
      say "\t$_ => $inner->{$_}" for sort keys %$inner;
      Which, to me, is safer and saner.

                   "I'm fairly sure if they took porn off the Internet, there'd only be one website left, and it'd be called 'Bring Back the Porn!'"
              -- Dr. Cox, Scrubs

Re: hash of hashes
by 2teez (Vicar) on Apr 18, 2013 at 04:00 UTC

    Or simply do like so:

    use warnings; use strict; use feature 'say'; my $ret = { room1 => { tag => 5, status => 'lazy', id => 5823 }, room2 => { tag => 10, status => 'active', id => 1234 }, }; for my $room ( sort keys $ret ) { say $room, ' : ', join "\t" => %{ $ret->{$room} }; }

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me