Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

perl - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...