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

Re: [MacPerl] Sorting



w e b s l a v e <PPRODOEHL@qgraph.com> spoke thusly:

>I've got some data I'd like to sort, and I'd like to be able to control
>the order, so if _my_ order is: 'red', 'green', 'blue', 'yellow'
>
>and the datain looks like: 'red 5', 'red 3', 'yellow', 'green'...
>
>is there an easy way to do this? I'm not sure how to compare an array to
>another array...?


To customize the sorting, you can temporarily prefix a sorting index to the
items, in a classic Schwartzian transform construct. (The following is but
a quick hack, not optimized for speed, style, elegance or coolness.)


#! perl rules -w
# Another fine(?) Newbieware(TM) product

use strict;

sub my_sort_order {
   my $param = shift;
   my @order = qw/red green blue yellow/;

   foreach my $i (0..$#order) {
      $param =~ /$order[$i]/i and return chr($i).$param;
   }

   $param;  # return unchanged if no match
}

my @data = ('red 5', 'yellow', 'red 3', 'green');

my @sorted = map  { $_->[0] }
             sort { $a->[1] cmp $b->[1] }
             map  { [ $_, my_sort_order($_) ] } @data;

print join(', ', @sorted), "\n";


HLV,
Andre

--
AndrŽ Leclerc
mailto:alecler@cam.org



***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch