所以我正在尝试编写一个子程序,它接受一个哈希参数,并为它添加几个键值对(通过引用).到目前为止,我有这个:
addParams(\%params); sub addParams { my(%params) = %{$_[0]}; #First argument (as a hash) $params{"test"} = "testing"; }
但出于某种原因,它似乎没有添加“测试”键.我是Perl的新手,但这不是你通过引用传递哈希的方式吗?先谢谢.
解决方法
您可以使用hash-ref而无需取消引用它:
addParams(\%params); sub addParams { my $params = shift; $params->{"test"} = "testing"; }
编辑:
my(%params) = %{$_[0]};
你实际上正在复制ref指向%{…}的内容.你可以通过一个细分的例子看到这个(没有功能,相同的功能):
my %hash = ( "foo" => "foo" ); my %copy = %{ \%hash }; $hash{"bar"} = "bar"; $copy{"baz"} = "baz"; print Dumper( \%hash ); print Dumper( \%copy );
跑:
$./test.pl $VAR1 = { 'bar' => 'bar','foo' => 'foo' }; $VAR1 = { 'baz' => 'baz','foo' => 'foo' };
两个哈希都有原始的’foo => foo’,但现在每个人都有不同的酒吧/巴兹.