Question: How do I reference perl hash? How do I deference perl hash? Can you explain it with a simple example?
Answer: In our previous article we discussed about Perl array reference. Similar to the array, Perl hash can also be referenced by placing the ‘\’ character in front of the hash. The general form of referencing a hash is shown below.
%author = ( 'name' => "Harsha", 'designation' => "Manager" ); $hash_ref = \%author;
This can be de-referenced to access the values as shown below.
$name = $ { $hash_ref} { name };
Access all keys from the hash as shown below.
my @keys = keys % { $hash_ref };
The above code snippet is same as the following.
my @keys = keys %author;
If the reference is a simple scalar, then the braces can be eliminated.
my @keys = keys %$hash_ref;
When we need to reference the particular element, we can use -> operator.
my $name = $hash_ref->{name};
Make reference to an anonymous Perl hash as shown below.
my $hash_ref = { 'name' => "Harsha", 'designation' => "Manager" };
De-Referencing this hash is same as we did for the above example (%author).
$name = $ { $hash_ref} { name };
Comments on this entry are closed.
how can i derefere hash reference to array?
Hi.
By “hash reference to an array”, do you mean this?
my %hash = (
‘mary’ => [‘female’, 18, ‘student’],
);
my $href = \%hash;
print ${$href}{‘mary’}->[2];
Hope this helps.
Hello.. i have some doubt related to PERL hash derefencing.. can anyone help me relate to this,
Like I have hash %abc = {
“ab’, “one”,
“cd’, “two”,
“ef’, “three”,
“gh’, {},
};
once i m printing the keys and values, i will get the value of “gh” key as “HASH{somenumber}”, but i dont want the hash ref and want “{}”.. what i will do.. please help me for this
Hi,
I am passing a scalar reference to a subroutine and modifying the value of this scalar within the subroutine. But when I read the scalar variable outside the subroutine it shows me the wrong value.