[英]How do I access a value stored in an array reference of hash references?
I'm working with the Samba::Smbstatus module for Perl. 我正在使用Perl的Samba :: Smbstatus模块。 The documentation says that values are returned in an array reference of hash references.
该文档说,值在哈希引用的数组引用中返回。 How would I go about accessing values?
我将如何获得价值?
I've tried a few methods and gotten nowhere. 我尝试了几种方法,却一无所获。
use Data::Dumper;
for my $hash_reference (@$aray_reference) {
# to check what keys are available
# print Dumper $hash_reference;
print $hash_reference->{attr1}, $hash_reference->{attr2};
}
use Data::Dumper and print the results. 使用Data :: Dumper并打印结果。 This may helps you to access the information you are looking for in the result you get.
这可能有助于您访问要获得的结果中要查找的信息。
Imagine your structure is something like: 想象一下您的结构是这样的:
my $data = [ {one=>1, two=>2}, {three=>3, four=>4} ];
# Access three key this way:
print $data->[1]->{three}, "\n";
I presume you're talking about the return from the services
method? 我想您是在谈论
services
方法的回报?
This is one way to access all the data in the structure. 这是访问结构中所有数据的一种方法。
First, the $services
array reference is dereferenced with @$services
, and you can then iterate over it with a for
loop like any other array. 首先,
$services
数组引用由@$services
取消引用,然后您可以像其他数组一样,使用for
循环对其进行迭代。
Each element $service
is a hash reference. 每个元素
$service
是一个哈希引用。 If you look again at the documentation, you will see that it has keys service
, pid
, machine
, and connected
. 如果再次查看该文档,将会发现它具有键
service
, pid
, machine
和connected
。 To access a hash element using a reference, you write $hashref->{key}
. 要使用引用访问哈希元素,请编写
$hashref->{key}
。 So I have added four printf
statements to print the values of those four elements. 因此,我添加了四个
printf
语句来打印这四个元素的值。
I haven't been able to test this, but the syntax checks out. 我还无法测试,但是语法检查出来了。
use strict;
use warnings;
use Samba::Smbstatus;
my $smbstats = Samba::Smbstatus->new;
my $services = $smbstats->services;
for my $service (@$services) {
printf "Service: %s\n", $service->{service};
printf "PID: %s\n", $service->{pid};
printf "Machine: %s\n", $service->{machine};
printf "Connected: %s\n", $service->{connected};
}
if $arrayRef is what you get, here is what you need to do to get to all the values 如果$ arrayRef是您获得的,这是获取所有值所需的操作
for my $hashRef (@$arrayRef) {
foreach my $key (keys %$hashRef) {
print $hashRef->{$key}, "\n";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.