I thought I was in the twilight zone earlier when I came to perlmonks to put down a question about sorting multidimensional hashes and the top question here was just that!
here's mine...
I have a 4 dimensional hash something like this: $logdata->{$log}->{$line}->{$category} = $value and I need to sort at the $log level by the value of a particular $category.
I already know what categories I need to sort by but don't want to write different subs for each.
My attempt went something like...
for my $log ( sort { if (!$query->param('merge')) { $a cmp $b } else { # it's merged so we have to sort at +log level rather than line level if ($query->param('sortby') eq 'time_as +c') { for my $line ( keys %{$logdata->{$l +og}} ) { my $timeA = $logdata->{$a}->{$l +ine}->{'time'}; my $timeB = $logdata->{$b}->{$l +ine}->{'time'}; $timeA cmp $timeB; } } elsif ($query->param('sortby') eq 'time +_des') { for my $line ( keys %{$logdata->{$l +og}} ) { my $timeA = $logdata->{$a}->{$l +ine}->{'time'}; my $timeB = $logdata->{$b}->{$l +ine}->{'time'}; $timeB cmp $timeA; } } } } keys %$logdata ) { my $loglines = $logdata->{$log}; for my $line ( sort keys %$loglines ) {
but since I am all "use strict;"-ed up, Perl moans that $log needs an explicit package name for $log in the for my $line ( keys %{$logdata->{$log}} ) { lines. This is more complicated than anything I have had to do to date and this is where I got stuck.
Against my better judgement I tried a foreach my $log (keys %$logdata) { above the two lines mentioned in the last paragraph but the output was not quite what I was looking for (a bunch of empty lines inamongst the UNsorted output).
I have a solution - make the first key in %$logdata "$log|$line" and remove a level from the hash but I figure there has to be a way to do this properly. Any help would be much appreciated.
larryk
In reply to Re: Re: sorting hash of hashes
by larryk
in thread sorting hash of hashes
by tevads
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |