Perl Hashes: $hash{key} vs $hash->{key}

Viewed 130

Perl newb here, sorry for a silly question, but googling -> for a coding context is tough... Sometimes, I will access a hash like this: $hash{key} and sometimes that doesn't work, so I access it like this $hash->{key}. What's going on here? Why does it work sometimes one way and not the other?

1 Answers

The difference is that in the first case %hash is a hash, and in the second case, $hash is a reference to a hash (= hash reference), thus you need different notations. In the second case -> dereferences $hash.

EXAMPLES:

# %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};

SEE ALSO:

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

Related