简体   繁体   English

Perl Hash引用

[英]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? 我是Perl的新手,但这不是你通过引用传递哈希的方式吗? Thanks beforehand. 先谢谢。

You can use the hash-ref without de-referencing it: 您可以使用hash-ref而无需取消引用它:

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 %{...}. 你实际上正在复制ref指向%{...}的内容。 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. 两个哈希都有原始的'foo => foo',但现在每个哈希都有不同的bar / baz。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM