Reputation: 4433
I am trying to access each member of a hash I have stored in an array in Perl. I have already seen Looping through an array of hashes in Perl, and I need a better way to access them. My end result will be splitting the taking each item (hash) in an array, storing the keys of that hash in a new array, storing the values of the array in a different array.
Edit: I changed they way my hashes get their data to reflect my code better. I didn't think it mattered, but it does.
<XML>
<computer>
<network>
<interface1>
<name>eht0</name>
<ip>182.32.14.52</ip>
</interface1>
<interface2>
<name>eth2</name>
<ip>123.234.13.41</ip>
</interface2>
</network>
</computer>
</xml>
my %interfaceHash;
for(my $i=0; $i < $numOfInterfaces; $i++ ){
my $interfaceNodes = $xmldoc->findnodes('//computer/network/interface'.($i+1).'/*');
foreach my $inode ($interfaceNodes->get_nodelist){
my $inetValue = $inode->textContent();
if ($inetValue){
my $inetField = $inode->localname;
push (@net_int_fields, $inetField);
push (@net_int_values, $inetValue);
}
}
for(my $i =0; $i< ($#net_int_fields); $i++){
$net_int_hash{"$net_int_fields[$i]"} = "$net_int_values[$i]";
}
push (@networkInterfaces, \%net_int_hash); #stores
}
Now, if I try to access the array, it wipes out what was stored in the hash.
Upvotes: 0
Views: 184
Reputation: 129559
Your problem is that a hash can NOT be a member of an array. Only a scalar can.
What you need in an array is not a hash, but a scalar reference to the hash:
push @networkInterfaces \%interface1; # \ is a reference taking operator
Then, to access an individual element of that hashref, you do
$networkInterfaces[0]->{iFaceName}; # "->{}" accesses a value of a hash reference
To access a whole hash (e.g. to get its keys), dereference using %{ hashref }
syntax:
foreach my $key ( keys %{ $networkInterfaces[0] } ) {
Upvotes: 1
Reputation: 242423
To build complex data structures in Perl, start with reading perldsc - Perl Data Structures Cookbook.
#!/usr/bin/perl
use warnings;
use strict;
my %interface1 = (iFaceName => 'eth0',
ipAddr => '192.168.0.43',
);
my %interface2 = (iFaceName => 'eth1',
ipAddr => '192.168.10.64',
);
my @networkInterfaces;
my @iFaceKeys;
my @iFaceVals;
push @networkInterfaces, \%interface1; # Note the backslash!
push @networkInterfaces, \%interface2;
for my $iFace (@networkInterfaces) {
push @iFaceKeys, keys %$iFace;
push @iFaceVals, values %$iFace;
}
Upvotes: 3
Reputation: 193
One good way to do this is to create an array of hash refs.
%first_hash = (a => 1, b => 2);
%second_hash = (a => 3, b => 4);
@array_of_hash_refs = ( \%first_hash, \%second_hash );
foreach $hash_ref (@array_of_hash_refs)
{
print "a = ", $hash->{a}, "\n";
print "b = ", $hash->{b}, "\n";
}
Keep in mind that perl has different syntax to access hash data depending on whether you are working with a hash object or a reference to a hash object.
$hash_ref->{key}
$hash{key}
Upvotes: 0