[tpm] dereferencing anonymous hashes

Jim Graham james.a.graham at gmail.com
Tue Apr 10 12:39:29 PDT 2007


  Tricky one:

    %x = (); 

 is an empty hash. The () is a list, and assigning it to a hash creates an empty hash. The '=>' notation that we're used to for hash
creation is in fact just sugar for the "," list operator. So you can do:

 %x = ( 'foo' => 1, 'bar' => 2); #-- it's a hash


 %x = ( 'foo' , 1, 'bar', 2); #-- looks like an array, but it's also a hash

And get the same thing.

  %x = {};

is weird. The "{}" creates an anonymous hash. Then assigning it to a regular hash (%x) uses the anon-hash ref as the key, and undef
as the value.

In the Perl debugger:

>perl -demo
  DB<1> %x = {}

  DB<2> foreach my $k ( keys %x) { print "$k\n";}

  Hope this helps;

  - jim

-----Original Message-----
From: toronto-pm-bounces+james.a.graham=gmail.com at pm.org [mailto:toronto-pm-bounces+james.a.graham=gmail.com at pm.org] On Behalf Of
Fulko Hew
Sent: April 10, 2007 3:26 PM
To: Rob Janes
Cc: tpm at to.pm.org
Subject: Re: [tpm] dereferencing anonymous hashes

On 4/10/07, Rob Janes <janes.rob at gmail.com> wrote:
> you're a php guy, right?

Nope.  Never seen PHP in my life... ain't gonna start now!

>  $x = (); is a list assignment to a scalar.  scalar conversion results in
> the scalar ($x that is) being assigned the count of the number of items in
> the list.  0 or zero.
>  $x = {}; assigns a reference to an anonymous hash.

OK, so I was getting frustrated and made a whole lot of transcription
errors to boot. :-(

The question should have been... whats the difference between:

%x = ();  and
%x = {};

because what fixed my problem was (transcribing correctly this time):

my %device = {};
$config{$cfg}{device} = \%device;
$device{$devid}{status} = 'OK';


my %device = %{$config{$cfg}{device}};
$status = $device{$devId}{status};
toronto-pm mailing list
toronto-pm at pm.org

More information about the toronto-pm mailing list