Perl 哈希:$hash{key} 与 $hash->{key}

sol*_*dau 5 perl reference key hashmap dereference

Perl newb 在这里,抱歉问了一个愚蠢的问题,但是在谷歌上搜索->编码上下文很困难......有时,我会像这样访问散列:$hash{key}有时这不起作用,所以我像这样访问它$hash->{key}。这里发生了什么?为什么它有时以一种方式工作而不是另一种方式?

Tim*_*and 6

不同之处在于,第一种情况%hash是散列,而在第二种情况下,$hash是对散列的引用(= 散列引用),因此您需要不同的符号。在第二种情况下->取消引用$hash

例子:

# %hash is a hash:
my %hash = ( key1 => 'val1', key2 => 'val2');

# Print 'val1' (hash value for key 'key1'):
print $hash{key1}; 

# $hash_ref is a reference to a hash:
my $hash_ref = \%hash;

# Print 'val1' (hash value for key 'key1', where the hash 
# in pointed to by the reference $hash_ref):
print $hash_ref->{key1}; 

# A copy of %hash, made using dereferencing:
my %hash2 = %{$hash_ref}

# $hash_ref is an anonymous hash (no need for %hash).
# Note the { curly braces } :
my $hash_ref = { key1 => 'val1', key2 => 'val2' };

# Access the value of anonymous hash similarly to the above $hash_ref:
# Print 'val1':
print $hash_ref->{key1};
Run Code Online (Sandbox Code Playgroud)

也可以看看:

perlreftut: https://perldoc.perl.org/perlreftut.html