How about this:

##################################

my %hash = (alpha => 'one', beta => 'two', gamma => 'zero', zeta =>
'cheese');

print "Sorted:\n";
foreach(sort {$hash{$a} cmp $hash{$b}} keys %hash){
        print "  $_  =>  $hash{$_}\n";
}

print "\n";
print "Unsorted:\n";
foreach(keys %hash){
        print "  $_  =>  $hash{$_}\n";
}

##################################

Also, if you want to do a numeric comparison, then you should change the
'cmp' to '<=>'.

-----Original Message-----
From: Kurtis [mailto:kurtis@;asdal.net]
Sent: Wednesday, November 06, 2002 4:10 PM
To: Timothy Johnson
Cc: [EMAIL PROTECTED]
Subject: Re: Hash Sorting?


Hey Timothy,

  I couldn't get it to work.......I know you can sort on keys, so I went out
the cheap way....I switched the values with my keys...it's no problem
because my values are unique also....

  If anyone is interested... as sort on keys...........

foreach $key (sort keys %hash)

  {
   $value=$hash($key);

#do something......

  }


----- Original Message -----
From: "Timothy Johnson" <[EMAIL PROTECTED]>
To: "'Perry, Alan'" <[EMAIL PROTECTED]>; <[EMAIL PROTECTED]>
Sent: Wednesday, November 06, 2002 6:17 PM
Subject: RE: Hash Sorting?


>
> Right you are.  sorry.
>
> -----Original Message-----
> From: Perry, Alan [mailto:aperry@;loislaw.com]
> Sent: Wednesday, November 06, 2002 3:17 PM
> To: [EMAIL PROTECTED]
> Subject: RE: Hash Sorting?
>
>
> I think the second example should be:
>
> foreach(sort {$hash{$a} cmp $hash{$b}} keys %hash){
>    do something...
> }
>
> Notice the %hash (and not $hash) at the end.
>
> -----Original Message-----
> From: Timothy Johnson [mailto:tjohnson@;sandisk.com]
> Sent: Wednesday, November 06, 2002 17:07
> To: 'Kurtis'; [EMAIL PROTECTED]
> Subject: RE: Hash Sorting?
>
>
>
> You can use the longer form of sort for this.  You may have seen this
> before:
>
> my @array = sort {$a cmp $b} @unsorted;
> #$a and $b are default variables for the sort command.
> #to reverse sort, you can reverse $a and $b.
>
> You can also do this:
>
> foreach(sort {$hash{$a} cmp $hash{$b}} keys $hash){
>    do something...
> }
>
> which I think is what you want.
>
> -----Original Message-----
> From: Kurtis [mailto:kurtis@;asdal.net]
> Sent: Wednesday, November 06, 2002 3:01 PM
> To: [EMAIL PROTECTED]
> Subject: Hash Sorting?
>
>
> Hello all......
>
>    Does anyone know how to sort a hash in ascending order on the value?
>
>   If possible, a little example!
>
> Thanks,
> Kurtis
>
> --
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
>
> --
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
>
> --
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
>


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to