你需要使用 - >引用哈希?

CJ7*_*CJ7 -4 perl hash reference

使用哈希,为什么以下两者都有效?

  • $hash{elem}
  • $hash->{elem}

Mat*_*cob 9

他们不"兼得".前者用于访问散列的元素,后者用于访问散列引用的元素.

use strict;
use warnings;
use 5.016;

my %hash = (one => 1);

say $hash{one};
say $hash->{one};
Run Code Online (Sandbox Code Playgroud)

输出:

Global symbol "$hash" requires explicit package name (did you forget to declare "my $hash"?) at 41474678.pl line 8.
Execution of 41474678.pl aborted due to compilation errors.
Run Code Online (Sandbox Code Playgroud)

如果您尝试使用散列引用(例如散列),则反向发生相同的错误:

my $href = {one => 1};

say $href->{one};
say $href{one};
Run Code Online (Sandbox Code Playgroud)

输出:

Global symbol "%href" requires explicit package name (did you forget to declare "my %href"?) at 41474678.pl line 8.
Execution of 41474678.pl aborted due to compilation errors.
Run Code Online (Sandbox Code Playgroud)

来自perldoc perlop的 "箭头操作员" :

" ->"是一个中缀解引用运算符,就像在C和C++中一样.如果右侧是a [...],{...}(...) 下标,则左侧必须分别是对数组,散列或子例程的硬引用或符号引用.(或者从技术上讲,一个能够持有硬引用的位置,如果它是用于赋值的数组或哈希引用.)