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

I can’t pretend to have really understood hash references, and this problem may be that my lack of understanding is causing me to try to do something that is not natural. Anyway, I am being returned a hash reference from a soap request, and am trying to retrieve an individual hash value.

I can iterate through the hash, and get the value I require, but cannot retrieve it directly; I’m assuming this should be possible.

All the commented out stanzas below work, but I would like to do something like the final uncommented stanza.

my $soap = SOAP::Lite->uri( $_[1] )->proxy( $_[2] )->getAllBrokerInfo( +); my @brokerInfos = @{ $soap->result }; for ( $i = 0 ; $i < @brokerInfos ; $i++ ) { $broker = @brokerInfos[$i]; #Get all values for each Broker - works #my @values = values %$broker; #foreach my $value (@values){print "$value\n";} #Get all keys for each Broker - works #my @keys = keys %$broker; #foreach my $key (@keys){print "$key\n";} #Get the values for all keys for each Broker - works #while (($key,$value) = each(%$broker)) { # print "$key $value\n"; #} #Get the value for key engineWeight by iterating through all keys +- works while (($key,$value) = each(%$broker)) { if ( $key eq "engineWeight" ) { print "$key $value\n"; } } #Just get value for engineWeight for each Broker - does not work print "%$brokers{'engineWeight'}\n"; }
The output from this script is simply

%

%

%

%

%

(there are five Brokers)

Any help very much appreciated.

Cheers, Nigel

Replies are listed 'Best First'.
Re: Accessing hash data via a reference
by moritz (Cardinal) on Mar 21, 2011 at 11:01 UTC
    See perlreftut. The correct way is $hashref->{$key}.

    If that still comes out empty, maybe the hash ref doesn't contain the keys that you think it contains? Data::Dumper can answer that question for you, and many other questions related to your data structures.

      very many thanks moritz, my syntax was all wrong, this works great

      print "Weight $broker->{'engineWeight'}\n";
Re: Accessing hash data via a reference
by samarzone (Pilgrim) on Mar 21, 2011 at 12:04 UTC

    I am quite sure you haven't written use strict in your script. Furthermore you are not viewing warnings if use warnings is on

    How can you get any value in "brokers" when you have declared "broker" in the start of the loop!!!

    Even if it would have been "broker" it would give compile time error under use strict

    When you write %$broker{'engineWeight'} it will try to find the value of $broker{'engineWeight'} and will append to '%'. Since there is no hash like %broker (mind it - it is hash reference $broker) it will throw a compile time error.

    --
    Regards
    - Samar