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

(Ovid) Re: Anonymous Data Structures: How Do They Work?

by Ovid (Cardinal)
on Jan 14, 2002 at 01:38 UTC ( #138472=note: print w/replies, xml ) Need Help??

in reply to Anonymous Data Structures: How Do They Work?

An answer with a few digressions.

When you assign an anonymous data structure to a scalar, you still have a scalar. This scalar is what is referred to as the reference and the data that it points to is referred to as the referent. When a scalar contains a reference, it holds a couple of pieces of data. One is the address of the referent, the other piece of data is the type of data structure. You see these two pieces when you stringify the reference:

$ perl -e 'print [qw/1 2/]' ARRAY(0x97116c)

In Perl, of course, you can't access that memory location directly (well, you can use Devel::Pointer, but I wouldn't), but it's a convenient method of managing complex data structures:

my %foo = ( name => [ qw/ Ovid is a fool / ], date => { once => 'in a', blue => 'moon' } );

In the above example, 'date' contains a reference to an anonymous hash. One interesting thing to note about anonymous structures is that the typing prohibits you from directly using them as another data structure. You have to play around with it a bit. For example, you can't directly coerce a hash reference into an array, though you can assign a hash to an array.

$ perl -e '$h={a=>2,b=>3,c=>4};print %$h' a2b3c4 $ perl -e '$h={a=>2,b=>3,c=>4};print @$h' Not an ARRAY reference at -e line 1. $ perl -e '%h=(a=>2,b=>3,c=>4);@a=%h;print@a' a2b3c4

Why does this really have anything to do with anonymous data structures? Because everything in Perl boils down to scalars and how you manage them. You can create a scalar that is a reference to an array, or stuff that reference into an another array, or even itself! All of these references will contain the same value.

$ perl -e '@a=(1,2); $foo=\@a; push@a,\@a;print $foo, $/, $a[-1]' ARRAY(0x980028) ARRAY(0x980028)

All handwaving aside, it's all scalars and it doesn't matter how you store them.

I realize that the above was a bit of a ramble, but that's my story and I'm sticking to it!


Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://138472]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (11)
As of 2018-05-21 13:33 GMT
Find Nodes?
    Voting Booth?