Perl newb在这里,对一个愚蠢的问题感到抱歉,但是->
在编码上下文中使用谷歌搜索是很困难的……有时,我将这样访问一个哈希值:$hash{key}
有时不起作用,所以我会这样访问它$hash->{key}
。这里发生了什么?为什么有时它以一种方式而不是另一种方式起作用?
区别在于,在第一种情况下%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 $hashref->{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 $hashref->{key1};
也可以看看:
perlreftut:https://perldoc.perl.org/perlreftut.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句