我将以下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";
}
}
Run Code Online (Sandbox Code Playgroud)
我感谢任何反馈.谢谢.
因为您没有正确使用引用.你可能想重读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";
}
}
Run Code Online (Sandbox Code Playgroud)