in reply to RFC: Context tutorial

In the section Context Clash, you show some interesting effects of assigning a list of expressions separated by commas to a scalar. I was surprised at the results of the third example. (Intuition based on subroutine calls is incorrect because subroutine arguments are in list context.)

However, your statement

Note that an array or hash slice counts as a "list" for this behavior.

does not appear to agree with the perl debugger. I got the following from a quick test:

my @t = qw/one two/; my $y = ( 'larry', 'moe', @t ); print "$y\n"; # prints 2 $y = ( 'larry', 'moe', @t[0,1] ); print "$y\n"; # prints two
G. Wade

Replies are listed 'Best First'.
Re^2: RFC: Context tutorial
by kyle (Abbot) on Jan 13, 2009 at 21:04 UTC

    Thanks for your comment. I guess I need to clarify that. The code you show does just what I would expect and also what I thought I described.

    The array slice, @t[0,1], would be a list but for the scalar context. Because of the context, it evaluates to the last item in that list (i.e., $t[1]). This kind of behavior was the subject of Why does assignment change the result?, if you want to read about it more.

    Before I post to Tutorials, I'll probably add your example to the others in that section to make this more obvious and probably also reword the line you quoted.

    Thanks again for pointing this out.

      I understand what it did. What I feel you were unclear about is the difference between:

      my $y = ( 'moe', 'larry', @t );

      and

      my $y = ( 'moe', 'larry', @t[0,1] );

      They react differently, and it takes a little thought to see why.

      G. Wade

        I see. Yes, thanks for clarifying further. An array in scalar context evaluates to the number of items in the array, but the array slice is a list. Now that I think about it, a whole section of "context clash" could be how arrays and hashes behave in list and scalar context, or maybe another section still.

        Thanks again for your input!