Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't ||= work with arrays?

I use the ||= operator to provide default values for variables, like

$x ||= 1;

I tried to use this syntax with an array but got a syntax error:

@array||= 1..3; 
Can't modify array dereference in logical or assignment (||=) ...

What does it mean and how should I provide arrays with default values?

like image 501
planetp Avatar asked Dec 08 '10 09:12

planetp


1 Answers

Because || is a scalar operator. If @array||= 1..3; worked, it would evaluate 1..3 in scalar context, which is not what you want. It's also evaluating the array in scalar context (which is ok, because an empty array in scalar context is false), except that you can't assign to scalar(@array).

To assign a default value, use:

@array = 1..3 unless @array;

But note that there's no way to tell the difference between an array that has never been initialized and one that has been assigned the empty list. It's not like a scalar, where you can distinguish between undef and the empty string (although ||= doesn't distinguish between them).

eugene y found this perl.perl5.porters message (the official Perl developers' mailing list) that goes into more detail about this.

like image 108
cjm Avatar answered Sep 21 '22 20:09

cjm