Perl modifies a hash reference in a routine

I'm having trouble understanding hash links and changing the hash instead of returning it. I want to write a subroutine that will return a value from a hash, and also change the hash. I ran into some coding issues. So, I wrote the following basic code to understand how to modify the hash in place.

#!/usr/local/bin/perl #Check hash and array references #Author: Sidartha Karna use warnings; use strict; use Data::Dumper; sub checkHashRef{ my ($hashRef, $arrVal) = @_; my %hashDeref = %{$hashRef}; $hashDeref{'check'} = 2; push(@{$arrVal}, 3); print "There:" ; print Dumper $hashRef; print Dumper %hashDeref; print Dumper $arrVal } my %hashVal = ('check', 1); my @arrVal = (1, 2); checkHashRef(\%hashVal, \@arrVal); print "here\n"; print Dumper %hashVal; print Dumper @arrVal; 

Observed output:

 There:$VAR1 = { 'check' => 1 }; $VAR1 = 'check'; $VAR2 = 2; $VAR1 = [ 1, 2, 3 ]; here $VAR1 = 'check'; $VAR2 = 1; $VAR1 = 1; $VAR2 = 2; $VAR3 = 3; 

From the output, I assumed that changes to hashDeref do not change the data in the link. Do I understand correctly? Is there a way to change the hash variable instead.

+7
source share
1 answer

This makes a (shallow) copy of %hashVal :

 my %hashDeref = %{$hashRef}; 

hash-ref $hashRef still points to %hashVal , but %hashDeref not, it's just a copy. If you want to change the passed hash-ref in place, then work with the passed hash-ref:

 sub checkHashRef{ my ($hashRef, $arrVal) = @_; $hashRef->{'check'} = 2; #... 

This will leave your changes to %hashVal . In the case of an array, you never make a copy, you just play it in place:

 push(@{$arrVal}, 3); 

and the change to $arrVal displayed in @arrVal .

+18
source

All Articles