techman2006 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am somewhat novice to Perl world. I was trying to write a sub which takes Hash as reference and populate the hash (passed as reference). But when I try to dump the data of the Hash I didn't get any output. Below is the code which I tried to do so
use strict; use warnings; use Data::Dumper; sub PopulateHash { my $hashParm = shift; my %hash1 = %$hashParm; %hash1 = ( 1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd'); print Dumper(\%hash1); } my %hash = (); PopulateHash(\%hash); print Dumper(\%hash);
The output of above code is given below
$VAR1 = { '4' => 'd', '1' => 'a', '3' => 'c', '2' => 'b' }; $VAR1 = {};
As this hash will be used at many places so I don't want to have a copy to avoid overheads. Any pointers about where I am missing will be great.

Replies are listed 'Best First'.
Re: Populating Hash passed to a sub as reference
by Kenosis (Priest) on Oct 24, 2013 at 18:48 UTC

    Oh, you're so very close! Try the following, instead:

    use strict; use warnings; use Data::Dumper; sub PopulateHash { my $hashParm = shift; %$hashParm = ( 1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd'); print Dumper(\%$hashParm); } my %hash = (); PopulateHash(\%hash); print Dumper(\%hash);

    Output:

    $VAR1 = { '4' => 'd', '1' => 'a', '3' => 'c', '2' => 'b' }; $VAR1 = { '4' => 'd', '1' => 'a', '3' => 'c', '2' => 'b' };

    Just use the dereferenced parm that was sent to populate your hash...

Re: Populating Hash passed to a sub as reference
by GotToBTru (Prior) on Oct 24, 2013 at 19:11 UTC
    One item of clarfication: you have

    PopulateHash(\%hash);
    which passes a reference to %hash to the subroutine PopulateHash.

    You create a new hash, %hash1, which is a copy of the old, %hash. Both are empty in this case.

    my %hash1 = %$hashParm;
    The changes in the subroutine are made to the new hash, which is a separate from the original. That's why you don't see the changes in the main program.
Re: Populating Hash passed to a sub as reference
by Anonymous Monk on Oct 25, 2013 at 00:46 UTC
    See references quick reference and see the "References" section in Chapter 3 in the free book Modern Perl a loose description of how experienced and effective Perl 5 programmers work....You can learn this too.