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

Re: [MacPerl] Sorting Arrays



On Sat, May 22, 1999 at 08:49:09AM -0700, Jon and Joetta wrote:
> I apologize for mistiming the code in my e-mail.  I guess I did need
> more sleep : )  
> 
> However, the POD was indeed wrong.  It says to sort the values using the
> word "keys".  I didn't think of using the word values, so I appreciate
> the help.  However, as it turns out I can't use the elements if they are
> in an array, so I was wondering if it was possible to sort the values of
> the array while still keeping them in an array.

No, the documentation is not wrong.  You don't want to sort the values.
You want to sort the keys, based on the values, just as it shows.

And that's not an array, it's a hash.  Arrays are indexed by whole numbers,
hashes are indexed by strings.
Array: @foo
Hash:  %bar


The code you provided mixes up the names of all the variables (i.e. %test
or %age?), so I'm making up my own example.

%ranks = (
        John => 2,
        Bob  => 1,
        Tim  => 3,
);

@names = sort {$ranks{$a} <=> $ranks{$b}} keys %ranks;

foreach $name (@names) {
    print "$name\t$ranks{$name}\n";
}


Enjoy.

Ronald

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