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

Re: [MacPerl] Sorting



PPRODOEHL@qgraph.com (w e b s l a v e) wrote:

> 
> 
> 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...?

One way would be to create a hash with your data as they key, and
their priority as the value.

@in = ('red 5', 'red 3', 'yellow', 'green');
@list = qw/red green blue yellow/;
@pri{@list} = 0 .. $#list;

for $item (@in) {
  $item =~ /(\w+)\s*(\d*)/;
  my ($color, $num) = ($1, ($2 or 0));
  die "Invalid color: $color\n" unless exists $pri{$color};
  push @sorthelper, [ $pri{$color}, $num ];
}

@sorted = @in[ sort by_color_then_num 0 .. $#in ];

print map { "$_\n" } @sorted;

sub by_color_then_num {
  return $sorthelper[$a][0] <=> $sorthelper[$b][0] ||
         $sorthelper[$a][1] <=> $sorthelper[$b][1];
}

or by avoiding the temporary array:

@in = ('red 5', 'red 3', 'yellow', 'green');
@list = qw/red green blue yellow/;
@pri{@list} = 0 .. $#list;

@sorted = map {$_->[0] } 
             sort { $pri{$a->[1]} <=> $pri{$b->[1]} ||
                    $a->[2] <=> $b->[2] }
             map { /(\w+)\s*(\d*)/; [ $_,$1, ($2 or 0) ] } @in;

print map { "$_\n" } @sorted;


Keep in mind, though that this mailing list is supposed to be for
questions specific to the MacPerl environment, not general perl
questions. General Perl questions belong in places like
comp.lang.perl.misc.


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