Re: Sorting associative arrays in perl


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


> I've got a bizarre question, probably better suited to the perl-mongers
> list, but i've lost all info for that, and haven't seen a post in quite
> some time.
>
> I've got an associative array: %data
>
> which is initialized like this from a datafile
>
> $data{$timestamp} = value;
>
> I would like to:
>
> 1) sort ascending, primarily, by the value (value is not unique)
> 2) sort ascending, secondarily, by the timestamp (timestamp is
> unique)
> 3) print the array
>
> the output should resemble:
>
> 100, 200204311201
> 240, 200203192104
> 240, 200203192205
> 242, 200204301300
> 301, 200203302048
>
> I can't figure out how to write the sort subroutine to perform this
> type of sort.

I don't know of a way to do this in a one-step sort, but you could try this:

  %vals = map { $data{$_}, 1} keys %data;
  foreach $val (sort {$a <=> $b} keys %vals) {
    foreach $dt (grep { $data{$_} =~ /^$val$/ } sort keys %data) {
      print "$val, $dt\n";
    }
  }

And no, I'm not doing a numeric sort on the timestamp since all digits are
padded, it works just the same. :-)

--

--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 - 09:06:07 AKDT