Sunday, June 20, 2010

How to do Perl Hash Reference and Dereference

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

No comments:

Post a Comment

Post a Comment