开发者

In Perl, how to traverse an array of hashes loaded by YAML?

I load the following YAML stream into a Perl's array and I want to traverse the array associated with Field2.

use YAML;

my @arr = Load(<<'...');
---
Field1: F1
Field2:
 - {Key: v1, Val: v2}
 - {Key: v3, Val: v4}
---
Field1: F2
Field2:
 - {Key: v5, Val: v6}
 - {Key: v7, Val: v8}
...

foreach (@arr) {
    @tmp = $_->{'Field2'};   
    print $#tmp; # why it says 0 when I have 2 elements?

    # Also why does the below loop not work? 
    foreach ($_->{'Field2'}) {
    print $_->{'Key开发者_如何学JAVA'} . " -> " $_->{'Val'} . "\n";
 }
}

I appreciate any feedback. Thank you.


Because you are not using references correctly. You may want to reread perldoc perlreftut and perldoc perlref.

#!/usr/bin/perl

use strict;
use warnings;

use YAML;

my @arr = Load(<<'...');
---
Field1: F1
Field2:
 - {Key: v1, Val: v2}
 - {Key: v3, Val: v4}
---
Field1: F2
Field2:
 - {Key: v5, Val: v6}
 - {Key: v7, Val: v8}
...

for my $record (@arr) {
     print "$record->{Field1}:\n";
     for my $subrecord (@{$record->{Field2}}) {
         print "\t$subrecord->{Key} = $subrecord->{Val}\n";
     }
}


You need to do some exercises with data structures and references. This works:

use 5.010;
use strict;
use warnings FATAL => 'all';

use YAML qw(Load);

my @structs = Load(<<'...');
---
Field1: F1
Field2:
 - {Key: v1, Val: v2}
 - {Key: v3, Val: v4}
---
Field1: F2
Field2:
 - {Key: v5, Val: v6}
 - {Key: v7, Val: v8}
...

# (
#     {
#         Field1 => 'F1',
#         Field2 => [
#             {
#                 Key => 'v1',
#                 Val => 'v2'
#             },
#             {
#                 Key => 'v3',
#                 Val => 'v4'
#             }
#         ]
#     },
#     {
#         Field1 => 'F2',
#         Field2 => [
#             {
#                 Key => 'v5',
#                 Val => 'v6'
#             },
#             {
#                 Key => 'v7',
#                 Val => 'v8'
#             }
#         ]
#     }
# )

foreach (@structs) {
    my $f2_aref = $_->{'Field2'};
    print scalar @{ $f2_aref }; # 2

    foreach (@{ $f2_aref }) {
        say sprintf '%s -> %s', $_->{'Key'}, $_->{'Val'};
    }

#     v1 -> v2
#     v3 -> v4
#     v5 -> v6
#     v7 -> v8
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜