arrays - How do I consolidate a hash in Perl? -
i have array of hash references. hashes contain 2 keys, user , pages. goal here go through array of hash references , keep running total of pages user printed on printer (this comes event logs). pulled data excel spreadsheet , used regexes pull username , pages. there 182 rows in spreadsheet , each row contains username , number of pages printed on job. script can print each print job (all 182) username , pages printed want consolidate down show: username 266 (i.e. show username once, , total number of pages printed whole spreadsheet.
here attempt @ going through array of hash references, seeing if user exists , if so, += number of pages user new array of hash references (a smaller one). if not, add user new hash ref array:
my $criteria = "user"; @sorted_users = sort { $a->{$criteria} cmp $b->{$criteria} } @user_array_of_hash_refs; @hash_ref_arr; $hash_ref = \@hash_ref_arr; foreach $index (@sorted_users) { %hash = (user=>"",pages=>""); if(exists $index{$index->{user}}) { $hash{pages}+=$index->{pages}; } else { $hash{user}=$index->{user}; $hash{pages}=$index->{pages}; } push(@hash_ref_arr,{%hash}); } but gives me error:
global symbol "%index" requires explicit package name @ ...
maybe logic isn't best on this. should use arrays instead? seems though hash best thing here, given nature of data. don't know how go slimming array of hash refs down username , total pages printed (i know seem redundant i'm trying clear). thank you.
as mkb mentioned, error in following line:
if(exists $index{$index->{user}}) however, after reading code, logic faulty. correcting syntax error not provide desired results.
i recommend skipping use of temporary hash within loop. work results hash directly.
for example:
#!/usr/bin/perl use strict; use warnings; @test_data = ( { user => "tom", pages => "5" }, { user => "mary", pages => "2" }, { user => "jane", pages => "3" }, { user => "tom", pages => "3" } ); $criteria = "user"; @sorted_users = sort { $a->{$criteria} cmp $b->{$criteria} } @test_data; %totals; $index (@sorted_users) { if (not exists $totals{$index->{user}}) { # initialize total user $totals{$index->{user}} = 0; } # add user's running total $totals{$index->{user}} += $index->{pages} } print "$_: $totals{$_}\n" keys %totals; this produces following output:
$ ./test.pl jane: 3 tom: 8 mary: 2
Comments
Post a Comment