为什么不跟|| =阵列工作? [英] Why doesn't ||= work with arrays?

查看:95
本文介绍了为什么不跟|| =阵列工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 || = 运营商为变量提供默认值,比如

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?

推荐答案

由于 || 是一个标量操作符。如果 @array || = 1..3; 工作,它会在标量环境评估 1..3 ,这是不是你想要的。它也评估在标量上下文中的数组(这是正常的,因为在标量上下文空数组是假的),但你不能分配给标(@array)

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

尤金Ÿ发现这个perl.perl5.porters消息(官方Perl开发人员邮件列表)的进入更详细的了解这一点。

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

这篇关于为什么不跟|| =阵列工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆