gpt4 book ai didi

arrays - 如何遍历 Perl 中对哈希数组的引用?

转载 作者:行者123 更新时间:2023-12-04 23:06:47 25 4
gpt4 key购买 nike

我有一个对传递给 perl 脚本中的子程序的 hases 数组的引用

这是代码:

sub mySub {
(my $resultref) = @_;
my @list = @$resultref;
print Dumper(@list);
foreach my $result (@list) {
print Dumper($result);
}
}

这是输出:
$VAR1 = [
{
'portName' => '1.1',
'ips' => [
'192.168.1.242'
],
'switchIp' => '192.168.1.20',
'macs' => [
'00:16:76:9e:63:47'
]
},
{
'portName' => '1.10',
'ips' => [
'192.168.1.119',
'192.168.1.3'
],
'switchIp' => '192.168.1.20',
'macs' => [
'd0:67:e5:f8:7e:7e',
'd0:67:e5:f8:7e:76'
]
},
];

$VAR1 = [
{
'portName' => '1.1',
'ips' => [
'192.168.1.242'
],
'switchIp' => '192.168.1.20',
'macs' => [
'00:16:76:9e:63:47'
]
},
{
'portName' => '1.10',
'ips' => [
'192.168.1.119',
'192.168.1.3'
],
'switchIp' => '192.168.1.20',
'macs' => [
'd0:67:e5:f8:7e:7e',
'd0:67:e5:f8:7e:76'
]
},
];

循环将整个数组放入 $result 变量中。我曾尝试将其取消引用为 @$result[0],但没有成功。

如何单独循环这些哈希?

谢谢!

最佳答案

Data::Dumper 的参数的 Dumper函数应该是引用。例如。:

use Data::Dumper;
my @array = ([1,2,3], [11,22,33]); # Two-dimensional array
print Dumper @array; # print array
print Dumper \@array; # print reference to array

输出:
$VAR1 = [
1,
2,
3
];
$VAR2 = [
11,
22,
33
];

$VAR1 = [
[
1,
2,
3
],
[
11,
22,
33
]
];

第二个打印为我们提供了一个变量中的整个结构。当你直接打印数组时,它会扩展到它的所有元素,所以......
print Dumper @array;

相当于:
print Dumper $array[0], $array[1], ..., $array[$#array];

因此,在您的情况下,只需执行以下操作:
sub mySub {
my ($resultref) = @_;
print Dumper $resultref;
}

访问内部变量:

看看 Data::Dumper的输出:
$VAR1 = [    # bracket denotes start of an array ref
{ # curly brackets = hash ref
'portName' => '1.1',
'ips' => [
'192.168.1.242'
],
'switchIp' => '192.168.1.20',
'macs' => [
'00:16:76:9e:63:47'
]
}, # hash ref ends, comma = new array element begins
{ # new hash ref
'portName' => '1.10',
'ips' => [
'192.168.1.119',
'192.168.1.3'
],
'switchIp' => '192.168.1.20',
'macs' => [
'd0:67:e5:f8:7e:7e',
'd0:67:e5:f8:7e:76'
]
}, # end of hash
]; # end of array

需要注意的是,数组的所有元素以及散列的所有值都是标量。因此,所有散列和数组都可以轻松分解为标量列表。
for my $aref (@$resultref) {  # starting array ref
for my $aref2 (@$aref) { # second level array ref
for my $href (@$aref2) # here begins the hash
local $\ = "\n"; # add newline to print for simplicity
print $href->{portName}; # printing a scalar
print for @{$href_>{ips}}; # printing an array ref w post-script loop
print $href->{switchIp};
print for @{$href->{macs}};
}
}
}

请注意使用箭头运算符取消引用引用。如果你有一个散列或数组,你会做 $array[0]$hash{$key} ,但通过使用引用,您可以“指向”引用中包含的地址: $array->[0]$hash->{$key} .

关于arrays - 如何遍历 Perl 中对哈希数组的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10382565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com