Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Hash by reference

so I'm trying to write a subroutine that takes a hash parameter and adds a couple key-value pairs to it (by reference). So far, I've got this:

addParams(\%params);

sub addParams
{
    my(%params) = %{$_[0]}; #First argument (as a hash)

    $params{"test"} = "testing";
}

But for some reason, It doesn't seem to add the 'test' key. I am new to Perl, but isn't this how you pass a hash by reference? Thanks beforehand.

like image 928
SuperTron Avatar asked May 06 '26 12:05

SuperTron


1 Answers

You can use the hash-ref without de-referencing it:

addParams(\%params);

sub addParams
{
    my $params = shift;

    $params->{"test"} = "testing";
}

EDIT:

To address your code's issue, when you do:

my(%params) = %{$_[0]};

You're actually making a copy of what the ref points to with %{...}. You can see this via a broken down example (no function, same functionality):

my %hash = ( "foo" => "foo" );
my %copy = %{ \%hash };

$hash{"bar"} = "bar";
$copy{"baz"} = "baz";

print Dumper( \%hash );
print Dumper( \%copy );

Run:

$ ./test.pl
$VAR1 = {
          'bar' => 'bar',
          'foo' => 'foo'
        };
$VAR1 = {
          'baz' => 'baz',
          'foo' => 'foo'
        };

Both hashes have the original 'foo => foo', but now each have their different bar/baz's.

like image 155
Christopher Neylan Avatar answered May 09 '26 03:05

Christopher Neylan