如何将元素推送到作为哈希值保存的数组引用中? [英] How can I push an element into an array reference held as a hash value?
问题描述
%data = (
'digits' => [1, 2, 3],
'letters' => ['a', 'b', 'c']
);
我怎样才能push
'4'
到$data{'digits'}
?
我是 Perl 的新手.那些 $
、@
、%
符号在我看来很奇怪;我来自 PHP 背景.
I am new to Perl. Those $
, @
, %
symbols look weird to me; I come from a PHP background.
推荐答案
push @{ $data{'digits'} }, 4;
$data{'digits'} 返回一个数组引用.将 @{} 放在它周围以取消引用它".同样,%{} 将取消引用哈希引用,而 ${} 将取消引用标量引用.
$data{'digits'} returns an array-reference. Put @{} around it to "dereference it". In the same way, %{} will dereference a hash reference, and ${} a scalar reference.
如果您需要将某些内容放入散列引用中,即
If you need to put something into a hash reference, i.e.
$hashref = { "foo" => "bar" }
您可以使用:
${ $hashref }{ "foo2" } = "bar2"
或箭头符号:
$hashref->{"foo2"} = "bar2"
在某种程度上,将引用视为与变量名称相同的东西:
In a certain way, think of a reference as the same thing as the name of the variable:
push @{ $arrayref }, 4
push @{ "arrayname" }, 4
push @arrayname , 4
事实上,这就是软引用".如果您没有开启所有严格性,您可以从字面上:
In fact, that's what "soft references" are. If you don't have all the strictnesses turned on, you can literally:
# perl -de 0
DB<1> @a=(1,2,3)
DB<2> $name="a"
DB<3> push @{$name}, 4
DB<4> p @a
1234
这篇关于如何将元素推送到作为哈希值保存的数组引用中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!