Perl Hash引用

Sup*_*ron 3 parameters perl hash reference subroutine

所以我正在尝试编写一个子程序,它接受一个哈希参数,并为它添加几个键值对(通过引用).到目前为止,我有这个:

addParams(\%params);

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

    $params{"test"} = "testing";
}
Run Code Online (Sandbox Code Playgroud)

但出于某种原因,它似乎没有添加"测试"键.我是Perl的新手,但这不是你通过引用传递哈希的方式吗?先谢谢.

Chr*_*lan 12

您可以使用hash-ref而无需取消引用它:

addParams(\%params);

sub addParams
{
    my $params = shift;

    $params->{"test"} = "testing";
}
Run Code Online (Sandbox Code Playgroud)

编辑:

要解决代码问题,请执行以下操作:

my(%params) = %{$_[0]};
Run Code Online (Sandbox Code Playgroud)

你实际上正在复制ref指向%{...}的内容.你可以通过一个细分的例子看到这个(没有功能,相同的功能):

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

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

print Dumper( \%hash );
print Dumper( \%copy );
Run Code Online (Sandbox Code Playgroud)

跑:

$ ./test.pl
$VAR1 = {
          'bar' => 'bar',
          'foo' => 'foo'
        };
$VAR1 = {
          'baz' => 'baz',
          'foo' => 'foo'
        };
Run Code Online (Sandbox Code Playgroud)

两个哈希都有原始的'foo => foo',但现在每个哈希都有不同的bar/baz.