How to do Perl Hash Reference and Dereference

by Balakrishnan Mariyappan on June 18, 2010

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

Linux Sysadmin Course Linux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. If you don’t know what these tools are and how to use them, you could be spending lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 3 comments… read them below or add one }

1 karthik February 6, 2012 at 5:37 am

how can i derefere hash reference to array?

2 Caitlin May 5, 2012 at 3:17 pm

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.

3 Rahu Patil September 16, 2014 at 3:30 am

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

Leave a Comment

Previous post:

Next post: