[Omaha.pm] Sort an array of arrayrefs by one of the elements of each arrayref

Jay Hannah jhannah at omnihotels.com
Mon Mar 13 14:48:16 PST 2006


How's this for an (err... another) obscure sample program? Yes, I'm
actually wresting this in real life today. :)

j


# Given an array of arrayrefs like so:

my @x = (
  [ 0,0,0, "blue" ],
  [ 1,1,1, "blue" ],
  [ 2,2,2, "yellow" ],
  [ 3,3,3, "yellow" ],
  [ 4,4,4, "yellow" ],
  [ 5,5,5, "red" ],
  [ 6,6,6, "red" ],
);

# Sort those arrayrefs if the following (arbitrary) order: yellow, blue,
red.

# Solution:

my @y = sort by_color_preference @x;

sub by_color_preference {
   my %pref = (
      yellow => 1,
      blue   => 2,
      red    => 3
   );
   # print $pref{$a->[3]} . " <=> " . $pref{$b->[3]} . "\n";
   $pref{$a->[3]} <=> $pref{$b->[3]};
}




More information about the Omaha-pm mailing list