在 Perl 中,如何遍历 YAML 加载的哈希数组?
我将以下 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";
}
}
我很感激任何反馈。谢谢。
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'} . " -> " $_->{'Val'} . "\n";
}
}
I appreciate any feedback. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为你没有正确使用参考文献。您可能需要重读
perldoc perlreftut
和perldoc perlref
。Because you are not using references correctly. You may want to reread
perldoc perlreftut
andperldoc perlref
.您需要对数据结构和引用进行一些练习。这有效:
You need to do some exercises with data structures and references. This works: