Iterate through Array of Hashes in a Hash in Perl

前端 未结 2 1302
小蘑菇
小蘑菇 2021-01-05 19:41

I have an Array of Hashes in a Hash that looks like this:

$VAR1 = {
          \'file\' => [
                      {
                        \'pathname\' =         


        
2条回答
  •  走了就别回头了
    2021-01-05 20:00

    There are no arrays of hashes in Perl, only arrays of scalars. It only happens that there's a bunch of syntactic sugar in case those scalars are references to arrays or hashes.

    In your example, $VAR1 holds a reference to a hash containing a reference to an array containing references to hashes. Yeah, that's quite a lot of nesting to deal with. Plus, the outer hash seems kinda useless, since it contains only one value. So yes, I think giving the inner array a meaningful name would definitely make things clearer. It's not actually a "copy": only the reference is copied, not the contents. All of the following are equivalent:

    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 element of %{$ref} for a given key is ${$ref}{key} (or $$ref{key}). The braces can contain arbitrary code returning a reference, while the short version can only be used when a scalar variable already holds the reference.

    Once your array of references to hashes is in a variable, iterating over it is as easy as:

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

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

提交回复
热议问题