Adventure with references to lists and lists of references
Archive - Originally posted on "The Horse's Mouth" - 2010-12-26 07:32:16 - Graham EllisI remember an old game I used to play on DEC 10 (and VAX and PDP-11) computers - the original adventure game, perhaps ([see here]) which was pure text / instruction based and you traveled North, South, East and West through the colossal cave. And there was one are - the maze - where you could get rather lost between a little maze of twisting passages, little maze of twisty passages, little twisty maze of passages, maze of little twisting passages, maze of little twisty passages, maze of twisting little passages, maze of twisty little passages, twisting little maze of passages, twisting maze of little passages, twisty little maze of passages and a twisty maze of little passages!
And I was reminded about that the other day when I was differentiating in Perl between a list of scalars, a list of references to scalars, and a reference to a list of scalars.
A series of scalars - held in a collections that's ordered (numbered from 0 upwards and sortable) is a list in Perl ... and you can create a list of scalars using round brackets:
@numbers = (10,20,30,40);
If you want to hold pointers / references / addresses of scalars rather than the scalars themselves in a list, you'll add an extra \ character:
@again = \(10,20,30,40);
In Perl terms, that looks like a single pointer to the list but it's not - it's an exception to the usual syntax, and it returns a whole list of pointers.
If you're really looking for a single pointer to a whole list, you'll use square brackets:
$further = [10,20,30,40];
So ...
A list of scalars (@numbers):
10 20 30 40
A list of references to scalars (@again):
SCALAR(0x100800f20) SCALAR(0x100800f30) SCALAR(0x100800f40) SCALAR(0x100800f50)
and a reference to a list (of scalars, but we can't tell that from the output) ($further):
ARRAY(0x10082c270)
There's an extended example - showing how hashes and references to hashes and context fits in too - [here].