[tpm] dereferencing anonymous hashes

Fulko Hew fulko.hew at gmail.com
Tue Apr 10 11:58:33 PDT 2007


On 4/10/07, Fulko Hew <fulko.hew at gmail.com> wrote:
> I always seem to have a problem dereferencing anonymous hashes...
> (a mental block, or I'm just mental!)
>
> In a subroutine I create the thing as such:
>
> sub foo {
>   my $device = {};                           # create an anonymous hash
>   $config{$cfg}{device} = \$device;    # And stick it into the major data structure
>
> $device{$devId}{status) = 'ok';         # and populate the anonymous hash
> $device{$devId}{msgCnt}++;
> }
>
> Then later on I want to extract the status:
>
> my %device = ${$config{$cfg}{device}};
> $status = $device{$devId}{status};
>
> but this isn't quite right.  ;-(

Answering my own question...
I was close, but not cigar.  What I should have been using was:

my $device = ();
 ...
my %device = %{$config{$cfg}{device}};

because the reference I was trying to retrieve was a reference to a hash,
not a reference to a scalar as in my first 'n' tries.

I'm sure I had the dereference correct a number of times, but without
the anonymous hash creation correct at the same time, It didn't
work.... Nope, I just tried it as: my $device = {}; and that still
worked.  It makes me wonder then... whats the subtle difference
between
$x = () and $x = {} when dealing with hashes and their references?


More information about the toronto-pm mailing list