开发者

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 derefer开发者_开发问答ence in logical or assignment (||=) ...

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


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.


This page has a good explanation, imho:

op= can occur between any two expressions, not just a var and an expression, but the left one must be an lvalue in scalar context.

Since @x ||= 42 is equivalent to scalar(@x) = @x || 42, and you aren't allowed to use scalar(@x) as an lvalue, you get an error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜