DevLip
May 20th, 2004, 12:56 PM
I've created a multi-dimensional hash that I'm trying to sort.
$foo{'a'}{1} = 4;
$foo{'a'}{2} = 7;
$foo{'a'}{3} = 3;
$foo{'b'}{1} = 1;
$foo{'b'}{2} = 5;
$foo{'b'}{3} = 6;
$foo{'c'}{1} = 4;
$foo{'c'}{2} = 2;
$foo{'c'}{3} = 8;
I'm trying to sort the hash by user defined values (lets say 1 then 2) and then output 3. so I'd end up with something like:
6, 8, 1
I wrote a snippet to do this:
%new_list = ();
my $line_count = 0;
foreach $factor (@rev_factors){
@sorted = sort keys %old_list;
my @keys_sorted_by_factor =
map { $_->[1] }
sort { $a->[0] <=> $b->[0] or $a <=> $b }
map { [ $old_list{$_}{$factor}, $_ ] }
@sorted;
#keys %old_list;
$line_count = 0;
foreach $key (@keys_sorted_by_factor){
$new_list{$line_count} = $old_list{$key};
$line_count++;
}
%old_list = %new_list;
}
For each $factor in @rev_factors I try to sort the keys (line numbers in this case) of the hash and then sort it by the value in key $factor. Then I rebuild the list to match the new keys and go again for the next factor.
Problem is it doesn't work that is its really only sorted by the last factor I entered and all sorts done before that one are lost.
Can someone figure out why this isn't holding previous sorts?
$foo{'a'}{1} = 4;
$foo{'a'}{2} = 7;
$foo{'a'}{3} = 3;
$foo{'b'}{1} = 1;
$foo{'b'}{2} = 5;
$foo{'b'}{3} = 6;
$foo{'c'}{1} = 4;
$foo{'c'}{2} = 2;
$foo{'c'}{3} = 8;
I'm trying to sort the hash by user defined values (lets say 1 then 2) and then output 3. so I'd end up with something like:
6, 8, 1
I wrote a snippet to do this:
%new_list = ();
my $line_count = 0;
foreach $factor (@rev_factors){
@sorted = sort keys %old_list;
my @keys_sorted_by_factor =
map { $_->[1] }
sort { $a->[0] <=> $b->[0] or $a <=> $b }
map { [ $old_list{$_}{$factor}, $_ ] }
@sorted;
#keys %old_list;
$line_count = 0;
foreach $key (@keys_sorted_by_factor){
$new_list{$line_count} = $old_list{$key};
$line_count++;
}
%old_list = %new_list;
}
For each $factor in @rev_factors I try to sort the keys (line numbers in this case) of the hash and then sort it by the value in key $factor. Then I rebuild the list to match the new keys and go again for the next factor.
Problem is it doesn't work that is its really only sorted by the last factor I entered and all sorts done before that one are lost.
Can someone figure out why this isn't holding previous sorts?