Why does the goatse operator work?

前端 未结 3 872
一向
一向 2021-01-04 19:43

The difference between arrays and lists and between list and scalar context have been discussed in the Perl community quite a bit this last year (and every year, really). I

3条回答
  •  误落风尘
    2021-01-04 19:53

    You misunderstand. Lists evaluated in scalar context do not get their size. In fact, it is all but impossible to have a list in scalar context. Here, you have a scalar assignment with two operands, a scalar variable on the left, and a list assignment on the right (given scalar context by the scalar assignment). List assignments in scalar context evaluate to the number of items on the right of the assignment.

    So, in:

    1 $foo
    2 =
    3 ()
    4 =
    5 ('bar')
    

    2, a scalar assignment, gives 1 and 4 scalar context. 4, a list assignment, gives 3 and 5 list context, but nevertheless is itself in scalar context and returns appropriately.

    (When = is a list assignment or a scalar assignment is determined purely from the surrounding syntax; if the left operand is a hash, array, hash slice, array slice, or in parentheses, it is a list assignment, otherwise it is a scalar assignment.)

    This treatment of list assignments in scalar context makes possible code like:

    while ( my ($key, $value) = each %hash ) {
    

    where list-context each is an iterator that returns (in list context) one key and value for each call, and an empty list when done, giving the while a 0 and terminating the loop.

提交回复
热议问题