Can the empty list be in scalar context?

前端 未结 2 1048
谎友^
谎友^ 2021-01-13 09:50

There is a lie that a list in scalar context yields the last element of the list. This is a lie because (as the saying goes) you can\'t have a list in scalar context. What

相关标签:
2条回答
  • 2021-01-13 10:02

    List is a very generic word. You could possibly be referring to the list operator or to a list value.

    There is no comma in the code, so there is no list operator.

    There is no list context in the code, so there is no list value.

    Therefore, there is no list in

    my $s = ();
    

    Parentheses never create a list

    (Only indirectly when on the LHS of an assignment operator.)

    what do we call the empty list in scalar context

    Perl calls it a "stub" (as shown below), and that's truly what it is. It's a placeholder in the code where putting literally nothing would be disallowed.

    The stub is represented by "empty parentheses", so that's another name for it.

    I call it bad code. If you want to assign undef, assign undef.

    There is a lie that a list in scalar context yields the last element of the list.

    No, that's true. List values cannot exist in scalar context, so that leaves the list operator.

    The list operator aka the comma operator returns the last element of the list in scalar context.


    Compare the following. No mention of list:

    >perl -MO=Concise -e"my $s = ();"
    6  <@> leave[1 ref] vKP/REFC ->(end)
    1     <0> enter ->2
    2     <;> nextstate(main 1 -e:1) v:{ ->3
    5     <2> sassign vKS/2 ->6
    3        <0> stub sP ->4
    4        <0> padsv[$s:1,2] sRM*/LVINTRO ->5
    -e syntax OK
    

    There is a mention of a list

    >perl -MO=Concise -e"my @a = ();"
    7  <@> leave[1 ref] vKP/REFC ->(end)
    1     <0> enter ->2
    2     <;> nextstate(main 1 -e:1) v:{ ->3
    6     <2> aassign[t2] vKS ->7
    -        <1> ex-list lK ->4
    3           <0> pushmark s ->4
    -           <0> stub lP ->-
    -        <1> ex-list lK ->6
    4           <0> pushmark s ->5
    5           <0> padav[@a:1,2] lRM*/LVINTRO ->6
    -e syntax OK
    

    ...and it has nothing to do with the parens

    >perl -MO=Concise -e"my @a = 's';"
    8  <@> leave[1 ref] vKP/REFC ->(end)
    1     <0> enter ->2
    2     <;> nextstate(main 1 -e:1) v:{ ->3
    7     <2> aassign[t2] vKS ->8
    -        <1> ex-list lK ->5
    3           <0> pushmark s ->4
    4           <$> const[PV "s"] s ->5
    -        <1> ex-list lK ->7
    5           <0> pushmark s ->6
    6           <0> padav[@a:1,2] lRM*/LVINTRO ->7
    -e syntax OK
    
    0 讨论(0)
  • 2021-01-13 10:06

    It's more like a valueless expression which is equivalent to undef. Some more examples:

    $ perl -we 'print scalar( () )'
    Use of uninitialized value in print at -e line 1.
    
    $ perl -we 'print 0+()'
    Use of uninitialized value in addition (+) at -e line 1.
    
    0 讨论(0)
提交回复
热议问题