0

I am trying to pass reference of a hash into a subroutine defined in another module in order to increase performance. In the subroutine in this other module reference is dereferenced as:

sub subRoutine{
    my $hash_ref = $_[0];
    my %hash = %$hash_ref;

    $hash{$a_key} = $a_value;
}

So this changes the value of that key in this module BUT it doesn't change the value in the perl program where this subroutine is called. What is the reason and how can I avoid this? Is it correct to use references instead of passing hashed/returning hashed in order to improve performance?

Thanks in advance! Best wishes!

Genom
  • 158
  • 2
  • 11

3 Answers3

4

Don't dereference into a local copy, just use the reference:

$hash_ref->{$a_key} = $a_value;
ysth
  • 96,171
  • 6
  • 121
  • 214
4

Passing references is fine if you want to manipulate the original variable, as you do here. The problem is that you are creating a copy of the referenced hash right away, and operating on the copy.

The line my %hash = %$hash_ref; is creating a new hash and copying all the key/value pairs from the original hash. When you change this copy it has no effect on the original.

Just get rid of that line, and replace the line $hash{$a_key} = $a_value; with $hash_ref->{$a_key} = $a_value;. You are now referring to an element of the original hash, and changing it.

Charles Engelke
  • 5,569
  • 1
  • 29
  • 26
3

When you say %hash = %$hash_ref, you are dereferencing it to a local copy (subroutine scope). If you want to change the value of the hash you passed into the subroutine, use

$hash_ref->{$a_key} = $a_value.

Nate
  • 1,889
  • 1
  • 20
  • 40