Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^2: hash and array mismatch

by TGI (Parson)
on May 10, 2007 at 17:06 UTC ( [id://614696]=note: print w/replies, xml ) Need Help??


in reply to Re: hash and array mismatch
in thread hash and array mismatch

Very interesting!

At first glance your code didn't look right. So I read more carefully and saw what was bothering me:

push @{$dataPos{$data[$_]}}, $_ for 0 .. $#data;

You are pushing data onto an undefined value that is dereferenced as an array! The script should (I thought) die the first time through the for loop. But it works. So I did some experimentats and read the docs.

I found out that you can do this:

my $foo; # $foo is undefined push @$foo, 23; print "I found @{$foo}\n";

Further testing showed that:

push @{ undef() }, 99;
Died as I had expected.

Further tests show that unshift works the same way. Also, pop and shift will create array references.

my $foo = undef; shift @{$foo}; print "Foo: $foo\n"; # prints Foo: ARRAY(0x12121212)

The various docs don't mention this special behavior. Thanks for the education.


TGI says moo

Replies are listed 'Best First'.
Re^3: hash and array mismatch
by GrandFather (Saint) on May 10, 2007 at 19:19 UTC

    It is called "autovivification". Have a read through perlreftut and perlref.

    You have seen it happen in a light weight way whenever you assign a value to an array element that hadn't been used before. It is a little more interesting in the case of a reference which you are using for the first time, but is one of the underpinnings of creating and managing "interesting" data structures in Perl, as indeed was the case here.

    My pleasure, education is a large part of what PerlMonks is about.


    DWIM is Perl's answer to Gödel

      I knew that autovivification would let you do things like $foo{a}{b}{c} = 7; I just didn't know that it worked for push and friends as well. Which is funny, because in perlreftut, it discusses the push related aspect.

      I know I read perlreftut a few years ago. I guess this tidbit failed to stick.

      For reference purposes, you can also do:

      my ($foo, $bar, $baz); $foo->[1] = 92; # $foo = [92] print $bar->[0]; # $bar = []; print @{ $baz }; # DIES - $baz not in lvalue context, no autoviv.

      Thanks for the pointer to autovivification. I obviously didn't understand it properly when I was first learning, and never really came back to the subject. Methinks I need to carefully reread Chapter 8 of Programming Perl.


      TGI says moo

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://614696]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (8)
As of 2024-04-18 08:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found