为什么在 Perl 中访问数组和散列元素时需要 $? [英] Why do you need $ when accessing array and hash elements in Perl?

查看:42
本文介绍了为什么在 Perl 中访问数组和散列元素时需要 $?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然在Perl中数组和散列只能包含标量,那为什么在访问数组或散列元素时必须使用$来告诉解释器该值是标量呢?换句话说,假设你有一个数组 @myarray 和一个散列 %myhash,你为什么需要这样做:

Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assuming you have an array @myarray and a hash %myhash, why do you need to do:

$x = $myarray[1];
$y = $myhash{'foo'};

而不仅仅是做:

$x = myarray[1];
$y = myhash{'foo'};

为什么上面有歧义?

如果在那个地方它不是一个 $ ,那么它不是非法的 Perl 代码吗?例如,以下所有内容在 Perl 中不都是非法的吗?

Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl?

@var[0];
@var{'key'};
%var[0];
%var{'key'};

推荐答案

切片不违法:

@slice = @myarray[1, 2, 5];
@slice = @myhash{qw/foo bar baz/};

而且我怀疑这就是您需要指定是否要从散列/数组中获取单个值的部分原因.

And I suspect that's part of the reason why you need to specify if you want to get a single value out of the hash/array or not.

这篇关于为什么在 Perl 中访问数组和散列元素时需要 $?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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