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

Re: [MacPerl-AnyPerl] Sorting Hashs



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:$_";
	}

   HTH,
   Bart.

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