Main Content

Perl references - $$var and $var notations

Archive - Originally posted on "The Horse's Mouth" - 2009-06-15 14:00:42 - Graham Ellis

In Perl, if I write:
$stuff = "Porridge";
then I'm setting up a variable to contain the value "Porridge".

If I write:
$stuffat = $stuff;
then I'm setting up a variable to contain the ADDRESS OF the variable $stuff.

So if $stuff was in memory at (hex)fe80 ... then $stuffat will be assigned that value 0xfe80. And we can look use it by using an extra $ character :
print $$stuffat;
which literally means "the contents of the contents of stuffat".


What use is this?

Lots ... not only for scalars, but for the addresses of lists too. If I write
$holder = \@biglist;
I have assigned a single scalar variable to point to what is potentially a huge dataset and (for starters) I can easily pass it around to various subs without the need to replicate the data.

Other languages have this concept - "pointer" - too. See & and * in C, and the use of & in PHP.