in reply to accessing a hash via reference

References: perlreftut, perldsc
# what is going on here? What am i dealing with? print " $token->[2]\n "; # how do i dereference this?
use Data::Dumper; print Dumper $token->[2]; # or w/o Data::Dumper print join(":", keys %{$token->[2]}), "\n";
my %hash = $token->[2]; # below wont work unless i feed it a hash # my $key; # foreach $key (keys %hash) { # print "at $key we have $hash{$key}\n"; # }
my $hash = $token->[2]; foreach my $key (keys %$hash) { printf "at %s we have %s\n", $key, $hash->{$key}; }
Or, alternatively (but the above is better, because this way below makes a copy of the data in the hash):
my %hash = %{$token->[2]}; foreach my $key (keys %hash) { printf "at %s we have %s\n", $key, $hash{$key}; }

Replies are listed 'Best First'.
Re^2: accessing a hash via reference
by richill (Monk) on Sep 03, 2006 at 13:30 UTC
    Thank you. Thats great.Just one question

    Is the difference between

         my %hash = %{$token->[2]}; and

    my %hash = $token->[2];

    The former trys to assign a string to a hash. Saying something like %hash = HASH(0x86b258)

    The latter assigns a hash to a hash by telling perl that whatever is inside %{} is definately a hash.Perl then gos and gets whatever $token->[2] points to and dereferences it.

      Need for <code></code> tags aside, the first is dereferencing a hash ref into a list and then assigning that list to your hash. The second is attempting to assign the hashref to the hash, which will get you a gripe about assigning an odd number of elements to a hash and a hash with one entry with a stringified representation of the hashref (what you're seeing) as the key.

        Thanks