This can get tricky. And there are sometimes strong opinions expressed on various aspects of this question -- not all of them in agreement. But on one thing there is agreement: "a list value is different from an array." Programming Perl, 3rd Edition, p. 73.
Consider this:
Some will argue that the first example does not involve a list, but rather the comma operator doing its scalar context thing (i.e. evaluating and throwing away the result of each value on the left (in turn) and then evaluating and returning the value on the right -- ultimately, the last one).print scalar ('a','b','c','d'); # prints 'd' my @array = ('a','b','c','d'); print scalar @array; # prints '4'
Others suggest that it is a 'list literal' (as opposed to an array) but that in a scalar context it is not behaving like a true list (written 'LIST' in Prog. Perl 3). As you can see these distinctions are not for the faint of heart.
It may be helpful to think of tacking 'literal' before the word 'list'. From that it becomes clearer that, for example: a (literal) list is stable in length while an array can be pushed or popped or changed in other ways. It may even help you make sense of the fact that, in a scalar context, arrays return the number of elements while (literal) lists return the last element of the list.
In a (literal) list, the comma operator is present and can do its thing. In an array, the comma operator that may have helped form it is now gone and we are left with a series of values accessable through the array variable.
All of which invites the question:
What does this print? Answer: '2' This is the last item in the literal list (i.e. @array1) which is then evaluated in a scalar context returning the number of elements in @array1. Notice that in the treatment of the literal list, the contents of @array1 were not flattened into the list as they would have been in a true list context (confused yet?) but rather, they were treated as a literal item returned by the comma operator and then evaluated to see what value to return.my @array1 = ('a','b'); print scalar ('x','y',@array1);
Again, a list is a literal. An array is a variable.
And don't even ask why
both print 'c' even though the qw(...) example contains no comma operators. Answer: because qw(...) is defined as returning a literal list (including the commas)... not an array!print scalar ('a','b','c'); print scalar qw(a b c);
You can find this and more on this subject here (brief and recommended) or in Programming Perl, 3rd Edition page 72-74 (longer and also helpful... or confusing... depending on how much sleep you had the night before).
Update:Read on below and take my bit above about 'literal' with a grain of salt.
In reply to How are arrays and lists different?
by dvergin
in thread array element seperators
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |