Iterate through hash in perl

319 Views Asked by At

I am new in Perl and struggling with hash. I want to loop through the hash, meaning I want to acces all the elements within 'obj' (the number can be different per 'obj'), e.g.:

   $VAR1 = { 'obj1' => ['par1', 
                         'par2', 
                         'par3'
                        ],
              'obj2' => ['par1', 
                         'par2', 
                         'par3',
                         'par4'
                        ]
    }

The code snippet below loops only through 'obj'. How can I access the elements within obj?

foreach my $key (keys %hash) 
{
   print ($key)
}

Any idea how can I access to par within objects or Perl-documentation reference? Thanks for the help!

1

There are 1 best solutions below

1
Timur Shtatland On
$VAR1 = { 'obj1' => ['par1', 
                     'par2', 
                     'par3'
                 ],
          'obj2' => ['par1', 
                     'par2', 
                     'par3',
                     'par4'
                 ]
      };

foreach my $obj ( keys %{ $VAR1 } ) {
    print "$obj => @{ $VAR1->{$obj} }\n";
}
# obj2 => par1 par2 par3 par4
# obj1 => par1 par2 par3

$VAR1 : a reference to a hash.
%{ $VAR1 } : the hash to which $VAR1 points to.
$obj : in the loop, this gets assigned to each of the keys of %{ $VAR1 }.
$VAR1->{$obj} : a reference to an array.
@{ $VAR1->{$obj} } : the array to which $VAR1->{$obj} points to.

REFERENCES:

perlreftut - Mark's very short tutorial about references: https://perldoc.perl.org/perlreftut