I have a reference to an array of hases that I pass to a subroutine in my perl script
This is the code:
sub mySub {
(my $resultref) = @_;
my @list = @$resultref;
print Dumper(@list);
foreach my $result (@list) {
print Dumper($result);
}
}
And this is the output:
$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'
]
},
];
The loop is putting the whole array into the $result variable. I have tried dereferencing it as @$result[0] with no success.
How do I loop those hashes individually?
Thanks!
The arguments to Data::Dumper‘s
Dumperfunction should be references. E.g.:The output:
The second print gives us the entire structure in one variable. When you print the array directly, it expands into all its elements, so…
Is equivalent to:
So, in your case, just do:
Accessing the inner variables:
Just take a look at
Data::Dumper‘s output:Important to note here is that all elements of an array, and all the values of a hash are scalars. Therefore, all hashes and arrays can easily be broken up into a list of scalars.
Note the use of the arrow operator to dereference a reference. If you have a hash or array you would do
$array[0]or$hash{$key}, but by using a reference, you “point” to the address contained in the reference instead:$array->[0]or$hash->{$key}.