imagineerThat
imagineerThat

Reputation: 5553

Perl: references of enumerated lists

I'm reading "Perl 5 Tutorial by Chan Bernard Ki Hong. He states...

Be careful of enumerated lists as a special case! As indicated on the perlref manpage, taking a reference of an enumerated list evaluates to a list of references of the list elements.

I'm not sure what the difference between an "enumerated list" and an "array" is.

He gives a reference example for an array:

$arrayref = \@array;

And one for an enumerated list:

@list = \($a, $b, $c); # Actually (\$a, \$b, \$c)

The enumerated list, ($a, $b, $c), looks like an array to me. What am I not seeing here?

So if @array = ($a, $b, $c), and $arrayref = \@array, then wouldn't @$array be ($a, $b, $c)?

Upvotes: 0

Views: 111

Answers (2)

abatie
abatie

Reputation: 169

I would think of it as "a list is a constant array":

@array = ("list item 1", "list item 2", "list item 3");

You can't do something like:

("list item 1", "list item 2", "list item 3")[1] = "list item 2a";

because you can't change a constant, but you could do:

$array[1] = "list item 2a";

because you copied the list into an array above and now it's a variable.

In your example, yes, they are all really arrays:

#!/usr/bin/perl

use strict;

my $a = 1;
my $b = 2;
my $c = 3;

# copy a list into an array
my @array = ($a, $b, $c);

# create a reference to an arrayr
my $arrayref = \@array;

# copy a list of variable references into an array
my @list = \($a, $b, $c);

print "before:\n";
for (my $i=0; $i < 3; $i++) {
print "array[$i]: $array[$i]\n";
print "arrayref[$i]: $arrayref->[$i]\n";
print "list[$i]: ${$list[$i]}\n";
}

$array[1] = "2a";
$arrayref->[1] = "2a";
# ok, really a reference to a constant, which shouldn't be mixed in
# with references to variables, but for simplicity...
$list[1] = \"2a";

print "\nafter:\n";
for (my $i=0; $i < 3; $i++) {
print "array[$i]: $array[$i]\n";
print "arrayref[$i]: $arrayref->[$i]\n";
print "list[$i]: ${$list[$i]}\n";
}

exit 0;

output:

before:
array[0]: 1
arrayref[0]: 1
list[0]: 1
array[1]: 2
arrayref[1]: 2
list[1]: 2
array[2]: 3
arrayref[2]: 3
list[2]: 3

after:
array[0]: 1
arrayref[0]: 1
list[0]: 1
array[1]: 2a
arrayref[1]: 2a
list[1]: 2a
array[2]: 3
arrayref[2]: 3
list[2]: 3

Upvotes: 0

ysth
ysth

Reputation: 98398

In perl, arrays are variable types, never a type of value. You can think of an array as the type of variable that stores a list as a value, but arrays and lists are otherwise quite distinct concepts. ($a,$b,$c) is a list (supposing it is in list context; in scalar context, it is the single value $c), not an array.

Normally, you use \ on variables (or at least lvalue scalars, as in \$hash{key}); the tutorial you are reading is just warning about the special case where \ is used on a list value or a slice: \($a,$b,$c) is equivalent to (\$a,\$b,\$c). \@array on the other hand simply produces a reference to the array.

Upvotes: 2

Related Questions