R – the difference between the scalar and list contexts in Perl

listperlscalar

What is the difference between the scalar and list contexts in Perl and does this have any parallel in other languages such as Java or Javascript?

Best Solution

Various operators in Perl are context sensitive and produce different results in list and scalar context.

For example:

my(@array) = (1, 2, 4, 8, 16);
my($first) = @array;
my(@copy1) = @array;
my @copy2  = @array;
my $count  = @array;

print "array: @array\n";
print "first: $first\n";
print "copy1: @copy1\n";
print "copy2: @copy2\n";
print "count: $count\n";

Output:

array: 1 2 4 8 16
first: 1
copy1: 1 2 4 8 16
copy2: 1 2 4 8 16
count: 5

Now:

  • $first contains 1 (the first element of the array), because the parentheses in the my($first) provide an array context, but there's only space for one value in $first.
  • both @copy1 and @copy2 contain a copy of @array,
  • and $count contains 5 because it is a scalar context, and @array evaluates to the number of elements in the array in a scalar context.

More elaborate examples could be constructed too (the results are an exercise for the reader):

my($item1, $item2, @rest) = @array;
my(@copy3, @copy4) = @array, @array;

There is no direct parallel to list and scalar context in other languages that I know of.