Iterating through a hash array in a hash in Perl

I have a hash array in a hash that looks like this:

$VAR1 = { 'file' => [ { 'pathname' => './out.log', 'size' => '51', 'name' => 'out.log', 'time' => '1345799296' }, { 'pathname' => './test.pl', 'size' => '2431', 'name' => 'test.pl', 'time' => '1346080709' }, { 'pathname' => './foo/bat.txt', 'size' => '24', 'name' => 'bat.txt', 'time' => '1345708287' }, { 'pathname' => './foo/out.log', 'size' => '75', 'name' => 'out.log', 'time' => '1346063384' } ] }; 

How can I iterate over these "file entries" in a loop and access its values? Is it easier to copy my @array = @{ $filelist{file} }; so that i only have an array of hashes?

+4
source share
2 answers

No need to copy:

 foreach my $file (@{ $filelist{file} }) { print "path: $file->{pathname}; size: $file->{size}; ...\n"; } 
+13
source

There are no hash arrays in Perl, only scalar arrays. It happens that there is a bunch of syntactic sugar if these scalars are references to arrays or hashes.

In your example, $ VAR1 contains a hash reference containing a reference to an array containing hash references. Yes, this is quite a bit of nesting. In addition, an external hash seems useless since it contains only one value. So yes, I think that giving a meaningful name to the inner array will certainly make things clearer. This is actually not a “copy”: only the link is copied, not the content. All of the following equivalents:

 my @files = $VAR1 -> {file} # dereferencing with the -> operator my @files = ${$VAR1}{file} # derefencing with the sigil{ref} syntax my @files = $$VAR1{file} # same as above with syntactic sugar 

Note that when using the sigil {ref} syntax, the sigil obeys the same rules as usual: %{$ref} (or %$ref ) is the hash referenced by $ ref, but the %{$ref} element for this key - ${$ref}{key} (or $$ref{key} ). The brackets can contain arbitrary code that returns the link, while the short version can be used only when the scalar variable already contains the link.

When your array of hash references is in a variable, iterating over it is as simple as:

 for (@files) { my %file = %$_; # do stuff with %file } 

See: http://perldoc.perl.org/perlref.html

+3
source

All Articles