[英]Perl hash add values
I am trying to push values into hash.我正在尝试将值推入散列。 I want to add the values under 'par3'.
我想在“par3”下添加值。 eg
例如
$VAR1 = { 'obj1' => ['par1',
'par2',
'par3' => ['par4','par5','par6',....]]}
I should also be able to add elements into 'par3' in case 'obj1'-'par1'-'par2'-'par3' matches.如果 'obj1'-'par1'-'par2'-'par3' 匹配,我还应该能够将元素添加到 'par3' 中。 So far I have this, but I can't figure out how can I add "the second level" under 'par3':
到目前为止,我有这个,但我不知道如何在“par3”下添加“第二级”:
push @{$a{$obj}},$par1,$par2,$par3
[ ... ]
is a reference to an array. [ ... ]
是对数组的引用。 Array elements are scalars.数组元素是标量。 So it is not possible to directly have the structure you seem to be requesting (ie. the
par3 => [ ... ]
pseudocode from your question).因此,不可能直接拥有您似乎要求的结构(即您问题中的
par3 => [ ... ]
伪代码)。 See perldsc见perldsc
It's not obvious what you are trying to do but a couple of possible ideas might be to use a reference to a hash, or to replace the array with a hash:您要尝试做什么并不明显,但有几个可能的想法可能是使用对哈希的引用,或者用哈希替换数组:
use Data::Dumper;
$Var2a = {
'obj1' => [
'par1',
'par2',
{ 'par3' => undef, }
],
};
push @{ $Var2a->{obj1}[2]{par3} }, 'par4', 'par5', 'par6';
print Dumper $Var2a;
$Var2b = {
'obj1' => {
'par1' => undef,
'par2' => undef,
'par3' => undef,
},
};
push @{ $Var2b->{obj1}{par3} }, 'par4', 'par5', 'par6';
print Dumper $Var2b;
I think you want to add children to par3.我认为您想将孩子添加到 par3。 As such, I think you want pars to have children.
因此,我认为你希望帕斯有孩子。 If so, you need a different data structure.
如果是这样,您需要不同的数据结构。
# Ordered
my $obj1 = [
{ name => 'par1', children => [ ] },
{ name => 'par2', children => [ ] },
{ name => 'par3', children => [
{ name => 'par4', children => [ ] },
{ name => 'par5', children => [ ] },
{ name => 'par6', children => [ ] },
] },
];
or或者
# Unordered
my $obj1 = {
par1 => { },
par2 => { },
par3 => {
par4 => { },
par5 => { },
par6 => { },
},
};
To append par7 to par3's children, you would use要将 par7 附加到 par3 的孩子,你会使用
# Ordered
use List::Util qw( first );
my $par7 = { name => 'par7', children => [ ] };
my $par3 = first { $_->{ name } eq 'par3' } @$obj1
or die( "par3 not found" );
push @{ $par3->{ children } }, $par7;
or或者
# Unordered
$obj1->{ par3 }{ par7 } = { };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.