2

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!

Dana
  • 107
  • 9

1 Answers1

5
$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

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
  • 1
    And, I 'd add, `$VAR1->{$obj}->[1]`, de-references the second array element, etc. Also, I'd add a reference of "_Perl Data Structure Cookbook_", [perldsc](https://perldoc.perl.org/perldsc). – zdim Jul 21 '22 at 18:33