Can an empty list be in a scalar context?

There is a lie that a list in a scalar context gives the last element of a list. This is a lie because (as they say) you cannot have a list in a scalar context. What looks like a list in a scalar context is indeed a comma operator in a scalar context, and it has different behavior in a scalar context.

However, there is a loop hole in this logic: a null list (sometimes called an empty list). Characters are () defined as a null listperldoc perlglossary . Design

my $s = ();

is a valid code and returns undefin $s. This does not seem to be documented anywhere in perldoc(I did not check Camel), but it has a lot of code on it, so I think it is here to stay.

Now that the preamble is completed, the question is: if we cannot have a list in a scalar context, then what do we call an empty list in a scalar context and what is rational not to call it a list (since there are no commas in the scalar context)?

If you like this question, you might also like the discussion in P5P .

+5
source share
2 answers

A list is a very general word. Perhaps you mean a list operator or 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 an LHS assignment statement.)

,

Perl "" ( ), . , .

" ", .

. undef, undef.

, .

, . , .

aka - .


. :

>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

>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

... 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
+7

, undef. :

$ 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.
+1

All Articles