[Melbourne-pm] Unexpected hashref behaviour

Gary Monson gmonson at realestate.com.au
Thu Aug 16 22:44:41 PDT 2007


Hi Wes

It seems to me that it is autovivification as you guess, as if you do:

#!/bin/perl -w

use strict;
use Data::Dumper;

my $h = {};
$h->{ k } = undef;
print Dumper $h;
foreach my $k (keys %{ $h->{k} } ) {}
print Dumper $h;

then you get:

$ ~/perl/djp2.pl
$VAR1 = {
          'k' => undef
        };
$VAR1 = {
          'k' => {}
        };

So it is turning it into what you are treating it as.

It seems to make no difference if you have the $h->{k} = undef line or
not.  It does this when there is no such element beforehand, and when it
is undef.  When it has some other value, it reports an error, as
expected:

Can't use string ("1") as an ARRAY ref while "strict refs" in use....

>From http://en.wikipedia.org/wiki/Autovivification:

'Autovivification is the automatic creation of a reference when an
undefined value is dereferenced.'

This is, of course, what your script is doing - dereferencing the
undefined hash element.

Gary Monson
Software Developer

realestate.com.au
the biggest address in property

T: 03 8456 4357
E: gmonson at realestate.com.au
W: www.realestate.com.au 
ASX: REA

Warning - This email transmission may contain confidential information.
If you have received this transmission in error, please notify us
immediately on (61 3) 9897 1121 or reply by email to the sender. You
must destroy the email immediately and not use, copy, distribute or
disclose the contents. Thank you. 

-----Original Message-----
From: melbourne-pm-bounces+gmonson=realestate.com.au at pm.org
[mailto:melbourne-pm-bounces+gmonson=realestate.com.au at pm.org] On Behalf
Of Wesley Moore
Sent: Friday, 17 August 2007 3:23 PM
To: Melbourne Perlmongers
Cc: david.pitt at nab.com.au
Subject: [Melbourne-pm] Unexpected hashref behaviour

Hello all,
Wondering if anyone can shed some light on the behaviour that a
colleague noticed in some of our code, replicated below. My guess is
it has something to do with elements in a foreach loop being aliases
to the real element combined with autovivification, but its just that
- a guess.

Wes

#!/bin/perl -w

use strict;
use Data::Dumper;

my $h = {};
$h->{ k } = undef;
print Dumper $h;
foreach my $k ( @{ $h->{k} } ) {}
print Dumper $h;

$ ~/perl/djp2.pl
$VAR1 = {
          'k' => undef
        };
$VAR1 = {
          'k' => []
        };
_______________________________________________
Melbourne-pm mailing list
Melbourne-pm at pm.org
http://mail.pm.org/mailman/listinfo/melbourne-pm


More information about the Melbourne-pm mailing list