I am trying to create an array of hashes, and I am wondering how to reference each hash within the array?
For eg:
while(<INFILE>)
{
my $row = $_;
chomp $row;
my @cols = split(/\t/,$row);
my $key = $cols[0]."\t".$cols[1];
my @total = (); ## This is my array of hashes - wrong syntax???
for($i=2;$i<@cols;$i++)
{
$total[$c++]{$key} += $cols[$i];
}
}
close INFILE;
foreach (sort keys %total) #sort keys for one of the hashes within the array - wrong syntax???
{
print $_."\t".$total[0]{$_}."\n";
}
Thanks in advance for any help.
You don’t need
This:
is sufficient for what you are after. No special syntax needed to declare that your array will contain hashes.
There’s probably different ways of doing the
foreachpart, but this should work:[BTW, declaring
my @total;inside that loop is probably not what you want (it would be reset on each line). Move that outside the first loop.]And
use strict; use warnings;, obviously 🙂