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

Hello gurus, I have a rather bad code that looks like this.
use strict; my %h = ("foo" => 1, "bar" => 2); my %g = (); $g{\%h} = 1; my @k = keys %g; my $hashref = $k[0]; my %tmp = %$hashref; print $tmp{"foo"}
When I run this I get  Can't use string ("HASH(0x90fcc70)") as a HASH ref while "strict refs" in use Is there anyway to make it work? It is not possible to change the data structures used there.
Regards,
delip

Replies are listed 'Best First'.
Re: Dereferencing references
by tirwhan (Abbot) on Feb 09, 2006 at 10:50 UTC
    $g{\%h} = 1;

    does not actually store the reference to the %h hash in any way, all it does is add an element to the %g hash with 1 as the value and the string representation of the %h hash ("HASH(0x90fcc70)") as the key. If you really want to use this string representation as the key (not a good idea IMO) you'd do

    use strict; my %h = ("foo" => 1, "bar" => 2); my %g = (); $g{\%h} = \%h; my @k = keys %g; my $hashref = $k[0]; my %tmp = %{$g{$hashref}}; print $tmp{"foo"}

    I think you should use something more useful as the hash key, or, if you just want to store hash references in a data structure without meaningful keys, use an array instead:

    use strict; my %h = ("foo" => 1, "bar" => 2); push (my @g,\%h); my $hashref = $g[0]; print $hashref->{foo};

    Also, consider using more descriptive variable names (unless this is just an example and not your actual code).


    All dogma is stupid.
Re: Dereferencing references
by planetscape (Chancellor) on Feb 09, 2006 at 11:12 UTC
Re: Dereferencing references
by Fletch (Bishop) on Feb 09, 2006 at 13:33 UTC