Re: Sorting associative arrays in perl


Subject: Re: Sorting associative arrays in perl
From: Arthur Corliss (arthur@corlissfamily.org)
Date: Tue May 07 2002 - 16:43:01 AKDT


> To sort it first by value, then by key you'd use something like:
>
> my @sorted = sort { $data{$a} <=> $data{$b} || $a <=> $b }
> keys(%data);
>
> The way it works is if the values, $data{$a} and $data{$b}, are
> equal, the comparison operator returns 0, and the second branch is tested.
>
> You'd then print it with something like:
>
> while (my($timestamp, $value) = each(%data)) {
> print "$value, $timestamp\n";
> }
>
> Or, more idiomatically:
>
> print map { "$data{$_}, $_\n" } @sorted;
>
> This can all be combined:
>
> print
> map { "$data{$_}, $_\n" }
> sort { $data{$a} <=> $data{$b} || $a <=> $b }
> keys(%data);
>
> But that may not be as readable.

:-) There we go, learn something new all the time! There's more than one way
to skin that cat. . .

--

--Arthur Corliss Bolverk's Lair -- http://arthur.corlissfamily.org/ Digital Mages -- http://www.digitalmages.com/ "Live Free or Die, the Only Way to Live" -- NH State Motto

--------- To unsubscribe, send email to <aklug-request@aklug.org> with 'unsubscribe' in the message body.



This archive was generated by hypermail 2a23 : Wed May 08 2002 - 10:36:43 AKDT