≡ Menu

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 };
Add your comment

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

Comments on this entry are closed.

  • karthik February 6, 2012, 5:37 am

    how can i derefere hash reference to array?

  • Caitlin May 5, 2012, 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.

  • Rahu Patil September 16, 2014, 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

  • Preethi December 8, 2016, 1:37 pm

    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.

    my $svar = 0;
    &sub(\$svar);
    print $svar; //prints 0 instead of 1
    
    sub {
    my $svar_ref = shift;
    $$svar_ref = 1;
    }