array vs list
hideIn Perl, lists and arrays are not strictly the same thing. Though they will often be referred to interchangeably.
In internals sense an array is something that has a corresponding AV, which means that it can referenced and modified. A list is a temporary construct of an unmodifiable set of values on the stack.
Thus in the code
@foo = ( $a, $b, $c );
the left hand side of the = is an array, the right hand side is a list.
Taking the reference to an array results in a scalar holding a reference to the array.
my $array_ref = \@foo;
Taking a reference to a list results in a list of references to the elements of the list.
my ($a_ref,$b_ref,$c_ref) = \( $a, $b, $c );
The arguments to a subroutine are normally a list.
fnorble( $a, $b, $c );
When an array is used in list context it returns a list of the elements in the array, and because the arguments of a subroutine are normally in list context
fnorble( @foo );
normally passes a list of the elements of @foo not @foo itself.
Where things get a little confusing is that you can access the elements of both a list and array using the same notation:
$b_copy = $foo[1] $b_copy = ($a,$b,$c)[1];
but the list always uses slice indexing and the array only uses slice indexing when prepended with with the @ sigil instead of $:
sub index_value {
if (wantarray) {
print "this is list context\n";
return (0, 1, 2);
}
print "this is scalar context\n";
return 0;
}
my @array = (4, 5, 6);
print $array[index_value()], "\n"; #prints "this is scalar context\n4\n"
print @array[index_value()], "\n"; #prints "this is list context\n456\n"
print (4,5,6)[index_value()], "\n"; #prints "this is list context\n456\n"
However, this trick is useful because subroutines can be accessed in list context so you can do things like:
sub fnorble {
#add one to each value passed in and return the new values
my @return_values = map { $_ + 1 } @_;
return @return_values;
}
my @foo = (1, 2, 3, 4);
my $b_copy = (fnorble(@foo))[1]; #$b_copy now holds 3, the second value in the
#list (2, 3, 4, 5)