Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Accessing hash elements inside another hash

by JavaFan (Canon)
on Mar 11, 2009 at 14:58 UTC ( [id://749900]=note: print w/replies, xml ) Need Help??


in reply to Accessing hash elements inside another hash

Hard to answer that question. Your printing code iterates over %Data. You are populating %Queues. But you aren't putting hash(refs) as values of %Queues, but arrayrefs, which contain hashes. So you have hashes containing arrays containing hashes.

And your printing code assumes the keys of %Data are hashes. The never ever are. Hash keys are always strings. No exceptions. (Strings can be used as hashes if you want to use symbolic references. But I advice you not to. And if you want to anyway, you're are on your own).

  • Comment on Re: Accessing hash elements inside another hash

Replies are listed 'Best First'.
Re^2: Accessing hash elements inside another hash
by bar10der (Beadle) on Mar 11, 2009 at 15:05 UTC
    Sorry, made a mistake in putting code. Actually %queues is prepared and returned by a sub routine into %Data. So the code is -
    my %Data = getQueues(); while (my ($key,$value) = each(%Data)){ #print "$key = $value \n"; for(my ($k,$v) = each($key->{'Queues'})){ print "$k = $v \n"; } }
      You're use of $key in the inner loop is incorrect. It should be:
      my %Data = getQueues(); while (my ($key,$value) = each(%Data)){ #print "$key = $value \n"; for(my ($k,$v) = each($Data{$key}->{'Queues'})){ print "$k = $v \n"; } }
      In general, accessing all key/value pairs in a HoH will look like:
      foreach my $key (keys(%HoH)){ foreach my $otherKey (keys($HoH{$key})){ my $value = $HoH{$key}{$otherKey}; my $result = &DO_SOMETHING($value); } }
        You're use of $key in the inner loop is incorrect.

        Yours is too... a hash reference cannot be stored (directly) as a hash key, only as value. so that should look like

        my %Data = getQueues(); while (my ($key,$value) = each(%Data)){ #print "$key = $value \n"; for(my ($k,$v) = each(%$value)){ print "$k = $v \n"; } }

        although that snippet doesn't fit the OP's data structure, either. The following might work:

        while (my ($key,$value) = each(%Data)){ if (ref $value eq 'ARRAY') { for my $hashref (@$value) { print " $_ => $hashref->{$_}\n" for keys %$hashref; } } else { print "$key = $value \n"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://749900]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-26 00:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found