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

I have a sub get_vars_hash which returns a a reference to a hash.
#%vars has the structure $vars{$name} = [$local, $value] return \%vars
Back in main I have the following code
my $vars = get_vars_hash($file); Dumper(\%$vars); #just for testing. #outputs #$var1 = { # 'DATE'=>[ # 'G234_DATE', # 'ZERO' # ], # 'STOP'=>[ # 'G234_STOP'' # '60' # ] # } #Which is what I expected foreach $key (keys(%$vars)){ print "$key\n"; } #outputs #DATE #ARRAY(0x1df50b0) #STOP #ARRAY(0x1df5074)
Not what I expected. Am I dereferencing the hash incorrectly? One last note the code and sub are called from a button press in a Tk GUI if that has any relevents.
Update:Maybe I've not been clear, I didn't expect to see the array refs at all, in the second bit of code as don't think they are keys in the hash. Maybe I'd better go back to a look at hashes again?

Replies are listed 'Best First'.
Re: Whats happening to my hash ref.
by tinita (Parson) on Jun 01, 2004 at 12:03 UTC
    if Dumper outputs what you state above, and the loop over keys %$var outputs the array refs, then either your perl is broken or you're not posting your complete code.
    it's always recommendable to post a full code example with its output copied and pasted and not retyped.
    i think you retyped because you say this is the output from Dumper:
    # 'STOP'=>[ # 'G234_STOP'' # '60' # ]
    can't be, there's two apostrophes and a missing comma.
    here's my complete example:
      Thankyou Tinita, Your answer prompted me to look further then the end of my nose and look at my own work a little more objectively and found the problem lay entirely with me. I have fixed the problem and all is well now.
      Thanks for your help a very grateful Monk.
Re: Whats happening to my hash ref.
by BUU (Prior) on Jun 01, 2004 at 11:01 UTC
    You're dereferencing the hash reference perfectly. It's the Array references that the hash contains that you aren't dereferencing. As Data::Dumper itself tells you by the use of [] around the elements.
Re: Whats happening to my hash ref.
by Aragorn (Curate) on Jun 01, 2004 at 11:22 UTC
    You get what you ask for, i.e. the array reference, which you have to dereference properly to get the elements of the array:
    foreach $key (keys(%$vars)){ print "$key\n"; foreach $array_elem ({@$vars->{$key}}) { print "\t$array_elem\n"; } # You can also use something like this to get at the array # elements individually: # print $vars->{$key}->[0]; # first element }
    Arjen
Re: Whats happening to my hash ref.
by El Linko (Beadle) on Jun 01, 2004 at 11:28 UTC
    Dumper( $vars );
    There is no need to dereference the hash and then rereference it in the call to Dumper. Apart from that it looks ok. If this is a cut'n'paste of the real code then adding use warnings and use strict may show something up. If not then maybe adding in the exact code causing the problem will help.