如何迭代这个复杂数据结构的各个部分?
我有一个用 Data::Dumper 打印的对象:
$VAR1 = {
'record' => [
{
'text' => 'booting kernel',
'version' => '2',
'iso8601' => '2011-06-23 11:57:14.250 +02:00',
'event' => 'system booted',
'modifier' => 'na'
},
{
'text' => 'successful login',
'subject' => {
'sid' => '999',
'uid' => 'user',
'audit-uid' => 'user',
'tid' => '0 0 unknown',
'ruid' => 'user',
'rgid' => 'gsp',
'pid' => '999',
'gid' => 'gsp'
},
'version' => '2',
'iso8601' => '2011-06-23 11:58:00.151 +02:00',
'event' => 'login - local',
'return' => {
'retval' => '0',
'errval' => 'success'
},
'host' => 'unknown'
},
],
'file' => {
'iso8601' => '2011-06-23 11:57:40.064 +02:00'
}
};
我想打印导航这样的每个值一个哈希值。据我了解,是一个具有两个键(记录、文件)的哈希,记录指向哈希数组。
您能帮助实现该结构的每个值吗?
我尝试过:
my @array=$VAR1{'record'};
foreach (@array) {
print $_{'text'};
}
……但不起作用。
I have an object that I printed with Data::Dumper:
$VAR1 = {
'record' => [
{
'text' => 'booting kernel',
'version' => '2',
'iso8601' => '2011-06-23 11:57:14.250 +02:00',
'event' => 'system booted',
'modifier' => 'na'
},
{
'text' => 'successful login',
'subject' => {
'sid' => '999',
'uid' => 'user',
'audit-uid' => 'user',
'tid' => '0 0 unknown',
'ruid' => 'user',
'rgid' => 'gsp',
'pid' => '999',
'gid' => 'gsp'
},
'version' => '2',
'iso8601' => '2011-06-23 11:58:00.151 +02:00',
'event' => 'login - local',
'return' => {
'retval' => '0',
'errval' => 'success'
},
'host' => 'unknown'
},
],
'file' => {
'iso8601' => '2011-06-23 11:57:40.064 +02:00'
}
};
I want to print each value navigating such an hash. For what I understood is an hash with two keys (record, file) and record points to an array of hashes.
Can you please help reaching each value of this structure?
I tried:
my @array=$VAR1{'record'};
foreach (@array) {
print $_{'text'};
}
… but it does not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只想迭代它,您可以执行以下操作:
这并不像 Data::Dumper 那样完全漂亮地打印它,但如果您想对任意嵌套结构执行其他任何操作,则该技术可能很有用。不太了解。
If you just want to iterate over it, you can do something like this:
This doesn't exactly pretty print it like Data::Dumper does, but the technique might be useful if you want to do anything else with an arbitrary nested structure you don't know much about.
$VAR1{record}
是数组引用,而不是数组。要访问数组,您需要取消引用:数组中的每个元素都是哈希引用,因此:
$VAR1{record}
is an array reference, not an array. To get to the array, you need to dereference:Each element in the array is a hash reference, so:
$VAR1
是一个参考。您需要取消引用它。$VAR1->{record}
是一个参考。您也需要取消引用它。$_
也是一个引用,因此您需要取消引用它。perldoc perlreftut
$VAR1
is a reference. You need to dereference it.$VAR1->{record}
is a reference. You need to dereference it too.$_
is also a reference, so you need to dereference that.perldoc perlreftut