为什么在Perl访问数组和散列元素时,你需要$? [英] Why do you need $ when accessing array and hash elements in Perl?
问题描述
由于数组和哈希只能包含在Perl标量,你为什么要使用$来告诉间preTER该值是一个标访问数组或哈希的元素是什么时候?换句话说,假设你有一个数组 @myarray
和哈希%myhash
,为什么你需要做的:
$ X = $ myArray的[1];
$ Y = $ {myhash'富'};
,而不是仅仅做:
$ X = myArray的[1];
$ Y = {myhash'富'};
为什么上面的暧昧?
那岂不是违法的Perl code,如果它是什么,但在那个地方$?例如,是不是所有的下列非法在Perl?
@var [0];
@var {'键'};
%变种[0];
VAR%{'键'};
切片是不违法的:
@slice = @myarray [1,2,5];
@slice = {@myhash QW /富酒吧巴兹/};
和我怀疑这就是为什么你需要指定,如果你想获得一个值出来的散列/阵列或没有的部分原因。
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'};
instead of just doing :
$x = myarray[1];
$y = myhash{'foo'};
Why are the above ambiguous?
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'};
Slices aren't illegal:
@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屋!