[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl-AnyPerl] Sorting Hashs



Bart Lateur wrote:
> 
> On Fri, 10 Sep 1999 09:11:40 -0500, Richard L. Grubb wrote:
> 
> >What is a good way to sort the values in a hash?
> >
> >I know that hash key/valure pairs are not stored in any particular
> >order. Should I convert the hash into two lists, and reorder the list of
> >keys to keep in step with the list of values?
> 
> It depends on what exactly you need. If you need to output the hash in
> alphabetical order of the hash value, this will do nicely:
> 
>  @sortedkeys = sort { $hash{$a} cmp $hash{$b} || $a cmp $b } keys %hash;
>  foreach (@sortedkeys) {
>         print " * $_ -> $hash{$_}\n";
>  }
> 
> If you want to order a hash according to yet another property value, you
> either can turn the hash into a hash of records (anonymous hashes or
> anonymous arrays), or keep two hashes with the same keys, one for each
> property.
> 
>         opendir(DIR,$dir);
>         %file = map { $_ => { path => "$dir:$_", age => -M "$dir:$_" } }
>                 readdir(DIR);
> or
>         %file = map { $_ => [ "$dir:$_", -M "$dir:$_" ] } readdir(DIR);
> or
>         foreach (readdir(DIR)) {
>                 $path{$_} = "$dir:$_";
>                 $age{$_} = -M "$dir:$_";
>         }
> 

I ended up using the procedure titled "Sorting An Array by A Computable
Field" in the "Programming Perl" book on page 249 (the 1992 printing).

In summary, I converted the hash into array with each key joined to its
associated value with a colon.

So data structure
%hash = ('GJ 1001', '3.915', 'NN 3002', '19.942', 'NN 3003', '21.627',
'Gl   1', '8.800')
becomes
@data = ('GJ 1001:3.9149', NN 3002:19.9418', 'NN 3003:21.627', 'Gl  
1:8.7992')

The proceedure then sorts @data based on the value after the colon.

Thanks to Ronald and Bart for their help.
-- 
Richard L. Grubb
Boeing Wichita

==== Want to unsubscribe from this list?
==== Send mail with body "unsubscribe" to macperl-anyperl-request@macperl.org