Home > other >  Perl hash add values
Perl hash add values

Time:07-22

I am trying to push values into hash. I want to add the values under 'par3'. e.g.

$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. So far I have this, but I can't figure out how can I add "the second level" under 'par3':

push @{$a{$obj}},$par1,$par2,$par3

CodePudding user response:

[ ... ] 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). See 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;

CodePudding user response:

I think you want to add children to 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

# 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 } = { };
  • Related