Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a list of undef not a read-only or constant value in Perl?

Tags:

perl

Consider the following programs in Perl.

use strict;
use warnings;

my @foo = qw(a b c);
undef = shift @foo;

print scalar @foo;

This will die with an error message:

Modification of a read-only value attempted at ...

Using a constat will give a different error:

1 = shift @foo;

Can't modify constant item in scalar assignment at ...
Execution of ... aborted due to compilation errors.

The same if we do this:

(1) = shift @foo;

All of those make sense to me. But putting undef in a list will work.

(undef) = shift @foo;

Now it prints 2.

Of course this is common practice if you have a bunch of return values and only want specific ones, like here:

my (undef, undef ,$mode, undef ,$uid, $gid, undef ,$size) = stat($filename);

The 9th line of code example in perldoc -f undef shows this, butthere is no explaination.

My question is, how is this handled internally by Perl?

like image 433
simbabque Avatar asked Sep 07 '15 10:09

simbabque


1 Answers

Internally, Perl has different operators for scalar assignment and list assignment, even though both of them are spelled = in the source code. And the list assignment operator has the special case for undef that you're asking about.

like image 193
Calle Dybedahl Avatar answered Sep 30 '22 19:09

Calle Dybedahl