in reply to Re^3: Why does assignment change the result?
in thread Why does assignment change the result?

The "lists always return the last item and only arrays return the length" is a popular but very misleading meme.

An array in scalar context returns the number of elements. An array slice in a scalar context returns the last value of the list that would be returned in a list context. A "literal list" (a list of expressions enclosed in parens and separated by commas) in a scalar context evaluates the last expression in a scalar context and returns the resulting value. Note that this may not be the same as the last value that would be returned if this "list" were evaluated in a list context. A list assignment in a scalar context returns the number of values on the right-hand side of the list assignment.

The term "list" with regard to Perl is not a precise term meaning only one thing. There are lots of kinds of lists in Perl (and an array is a kind of list, especially if you define an array slice as a "list"). Each different type of "list" in Perl returns a different thing in a scalar context, usually something rather appropriate1.

There are lots of discussions of this around the Monastery so I'm bit surprised that so many participants of this thread remember so little from them. :)

- tye        

1 Note that what an array slice returns (or was it hash slices or both?) in a scalar context was never designed nor documented and was only implemented after a patch I wrote and forgot about years ago. It also happens to be one of the rare cases when Perl "makes a list (of scalar values on the stack) despite a scalar context and then throws all but one of them away", which Perl usually avoids.

Update: Had I better understood Perl's list/scalar contexts at the time I wrote the patch, I probably would have at least wanted to make the patch instead pass the scalar context inward to the array slice indices expression (or to the hash slice keys expression) so that only one index (key) was calculated and then used to determine which single element to return.

  • Comment on Re^4: Why does assignment change the result? ("list")