0

My understanding was that in Perl we pass hashes to functions by reference

Consider the following example, where we modify the hash in the modifyHash function

#!/usr/local/bin/perl

my %hash;

$hash{"A"} = "1";
$hash{"B"} = "2";


print (keys %hash);
print "\n";

modifyHash(\%hash);

print (keys %hash);
print "\n";

sub modifyHash {
    my $hashRef = @_[0];
    my %myHash = %$hashRef;
    $myHash{"C"} = "3";
    print (keys %myHash);
    print "\n";
}

The output of this script is:

AB
ABC
AB

I would have expected it to be:

AB
ABC
ABC

...as we pass the hash by reference.

What concept am I missing here about passing hashes to functions?

1
  • 2
    Can't explain why someone downvoted other than downvotes happen for many reasons, some irrational. Anyway, this action: my %myHash = %$hashRef; constitutes "pass by value" or "copy by value". There is no lingering binding between %myHash and $hashRef
    – DavidO
    Aug 7, 2015 at 20:11

2 Answers 2

5

That's because when you do my %myHash = %$hashRef;, you're taking a copy of the dereferenced $hashref and putting it into %myHash which is the same thing as my %myHash = %hash;, so you're not working on the referenced hash at all.

To work on the hash specified by the reference, try this...

sub modifyHash {
    my $hashRef = $_[0];
    $hashRef->{"C"} = "3";
    print (keys %$hashRef);
    print "\n";
}

As pointed out by ThisSuitIsBlackNot in the comments below, @_[0] is better written as $_[0]. You should always be using use strict; and use warnings;, as this would have been caught. Because you're sending in a reference, you could also have used my $hashRef = shift;.

2
  • 2
    my $hashRef = @_[0]; better written as my $hashRef = $_[0]; (which the OP would know if they used warnings) Aug 7, 2015 at 18:07
  • Totally agreed... either that or shift. I just copy/pasted for the example. I'll fix it for other readers in the future. Thanks.
    – stevieb
    Aug 7, 2015 at 18:11
1

The problem is with the assignment:

my %myHash = %$hashRef;

This is akin to saying:

$x = 5;
$y = $x;

You're not setting $y to reference the same spot in memory, you're just giving the value of $x to $y. In your example, you're creating a new hash (%myHash) and giving it the value of the hash stored at $hashRef. Any future changes are to the new hash, not the original.

If you want to manipulate the original, you should do something like:

${$hashRef}{"C"} = "3";

or

$hashRef->{"D"} = 4;

There might be a more elegant way of doing it, but as far as I know you want to work with the hash reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.