What's wrong with your "horrible" code is that you don't use the data in the outer loop. If written like that:
you can see that $outerField is declared but never used. You're actually just doing six times the same thing in a row.OUTER: foreach my $outerField (@fields[2,4,5,9,7,1]) { my %hash; INNER: foreach my $innerField(@fields[2,4,5,9,7,1]) { $hash{$innerField}++; } push @report, \%hash; }
If I were you, I'd get the result of the split into a hash instead of an array, because selecting them by number doesn't help reading.
use strict; use warnings; use Data::Dumper; my %report; my $nameCount=0; my @names = map { $_.++$nameCount } ('Key', ) x 10; # Here the names will be Key1 to Key10, # But you should actually give explicit names with something like # my @names = qw/Princess Leia Obiwan Kenobi Anakin Skywalker Darth Va +der Han Solo/; while (my $line = <DATA>) { my %fields; @fields{@names} = (split / /, $line); # Here we put the result into + a slice of %fields foreach my $name (@names) { my $value = $fields{$name}; $report{$name}{$value}++; # Auto vivification here, $report{$nam +e} magically becomes a hashref } } print Dumper \%report; __DATA__ 483 OS dx-32 1 charles list4 aardvark.com ty-off lx-on C 01 483 DS dx-14 1 james list3 23.456.12.7 ty-on lx-on B 01 769 XO dx-32 5 sully nolist widgets.com ty-on lx-on V 07
$VAR1 = {
'Key10' => {
'C' => 1,
'B' => 1,
'V' => 1
},
'Key2' => {
'XO' => 1,
'OS' => 1,
'DS' => 1
},
'Key1' => {
'483' => 2,
'769' => 1
},
'Key5' => {
'james' => 1,
'sully' => 1,
'charles' => 1
},
'Key8' => {
'ty-on' => 2,
'ty-off' => 1
},
'Key4' => {
'1' => 2,
'5' => 1
},
'Key6' => {
'nolist' => 1,
'list3' => 1,
'list4' => 1
},
'Key3' => {
'dx-32' => 2,
'dx-14' => 1
},
'Key7' => {
'aardvark.com' => 1,
'widgets.com' => 1,
'23.456.12.7' => 1
},
'Key9' => {
'lx-on' => 3
}
};
So if you want to access the information on the site name, and have named the seventh key "siteName", you just have to go for $report{siteName} instead of $report[7]
Appart from the use of a hash instead of an array, it's pretty much the same as LanX and BrotherUk's ones.
In reply to Re: array of hashes, categorized by array index
by Eily
in thread array of hashes, categorized by array index
by tevus_oriley
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |