【问题标题】:Perl Hashes: $hash{key} vs $hash->{key}Perl 哈希:$hash{key} 与 $hash->{key}
【发布时间】:2020-11-28 07:47:31
【问题描述】:

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

【问题讨论】:

标签: perl reference hashmap key dereference


【解决方案1】:

不同之处在于,在第一种情况下,%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};

另请参阅:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2010-09-14
    • 2013-03-09
    • 2014-06-15
    • 2015-10-12
    • 2019-06-15
    相关资源
    最近更新 更多