What is the difference between lists and arrays?

Take a look at perldoc -q "list and an array". The biggest difference is that an array is a variable, but all of Perl's data types (scalar, array and hash) can provide a list, which is simply an ordered set of scalars.

Consider this code

use strict;
use warnings;

my $scalar = 'text';
my @array = (1, 2, 3);
my %hash = (key1 => 'val1', key2 => 'val2');

test();
test($scalar);
test(@array);
test(%hash);

sub test { printf "( %s )\n", join ', ', @_ }

which outputs this

(  )
( text )
( 1, 2, 3 )
( key2, val2, key1, val1 )

A Perl subroutine takes a list as its parameters. In the first case the list is empty; in the second it has a single element ( $scalar); in the third the list is the same size as @array and contains ( $array[0], $array[1], $array[2], ...), and in the last it is twice as bug as the number of elements in %hash, and contains ( 'key1', $hash{key1}, 'key2', $hash{key2}, ...).

Clearly that list can be provided in several ways, including a mix of scalar variables, scalar constants, and the result of subroutine calls, such as

test($scalar, $array[1], $hash{key2}, 99, {aa => 1, bb => 2}, \*STDOUT, test2())

and I hope it is clear that such a list is very different from an array.

Would it help to think of arrays as list variables? There is rarely a problem distinguishing between scalar literals and scalar variables. For instance:

my $str = 'string';
my $num = 99;

it is clear that 'string' and 99 are literals while $str and $num are variables. And the distinction is the same here:

my @numbers = (1, 2, 3, 4);
my @strings = qw/ aa bb cc dd /;

where (1, 2, 3, 4) and qw/ aa bb cc dd / are list literals, while @numbers and @strings are variables.


Actually, this question is quite well answered in Perl's FAQ. Lists are (one of) methods to organize the data in the Perl source code. Arrays are one type of storing data; hashes are another.

The difference is quite obvious here:

my @arr = (4, 3, 2, 1);
my $arr_count  = @arr;
my $list_count = (4, 3, 2, 1);

print $arr_count, "\n"; # 4
print $list_count;      # 1

At first sight, there are two identical lists here. Note, though, that only the one that is assigned to @arr variable is correctly counted by scalar assignment. The $list_count stores 1 - the result of evaluating expression with comma operator (which basically gives us the last expression in that enumeration - 1).

Note that there's a slight (but very important) difference between list operators/functions and array ones: the former are kind-of omnivores, as they don't change the source data, the latter are not. For example, you can safely slice and join your list, like this:

print join ':', (4,2,3,1)[1,2]; 

... but trying to 'pop' it will give you quite a telling message:

pop (4, 3, 2, 1);
### Type of arg 1 to pop must be array (not list)...

Tags:

Arrays

List

Perl