Reputation: 543
I have a map structure in Perl, that I'm getting from some utility. The dump of which looks like this:
$VAR1 = {
'A0' => 'me_one',
'A2' => 'me_two',
'A6' => 'me_six'
}
I want to search if a particular key exists in the map. Say I would like to know if A4
is in the map.
Now if I use if (exists $map{'A4'})
, I get an error during build, at $map{
.
And if I use if (exists $map->{'A4'})
, I get no error, and I get the desired result. However everywhere I search on the internet, to check if a key exists in a map, the syntax in Perl is if (exists $map{key})
Now my inference is that what I get from utility is not a map, though still looks like a map to me from the dump. Any one has an idea what's going on? Thank you.
Edit: Thanks to @raina77ow's answer. Adding this to further his explanation.
my %map;
print $map{key};
my $map_ref = \%map; # The reference was what the utility was returning
print $map_ref->{key};
Upvotes: 2
Views: 542
Reputation: 106453
The $map{key}
line is used when you address a specific element of hash %map
. For example:
my %map = (
a => 'a',
b => 'b'
);
print $map{a}; # 'a'
The $map->{key}
line is used when you address a specific element of hashref $map
. ->
operator is used specifically to 'deference' a reference.
my $map_ref = {
a => 'a',
b => 'b'
};
print $map_ref->{a}; # 'a'
Note that in the first case the regular parenthesis are used, in the second case it's curly brackets (to define so-called anonymous hash
).
Upvotes: 4