我将以下YAML流加载到Perl的数组中,我想遍历与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'} . " -> " $_->{'Val'} . "\n";
}
}
我感谢任何反馈。谢谢。
答案 0 :(得分:6)
因为您没有正确使用引用。您可能需要重新阅读perldoc perlreftut
和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";
}
}
答案 1 :(得分:1)
您需要对数据结构和引用进行一些练习。这有效:
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
}