http://www.perlmonks.org?node_id=962078

Some of you may know that I sort almost everything I use. One day I came upon an idea to put all the different ways I sort things into a subroutine. Those who know me know that I like to randomize things too, so I added a random sort into the mix if a sort type is not chosen.

sub short_sorts { my ($a,$b,$type) = @_; # Legend: # cs = case sensitive # ci = case insensitive # a = ascending # d = descending # r = reverse (right to left) # n = numbers # l = length of value # Note: # If you put $b from the main script into $a in this subroutine and +use descending, # you will actually get the list returned in ascending order. my %sorts = ( 'cs-a' => sub { $_[0] cmp $_[1] }, 'cs-a-r' => sub { reverse($_[0]) cmp reverse($_[1]) }, 'cs-d' => sub { $_[1] cmp $_[0] }, 'cs-d-r' => sub { reverse($_[1]) cmp reverse($_[0]) }, 'ci-a' => sub { uc $_[0] cmp uc $_[1] }, 'ci-a-r' => sub { uc reverse($_[0]) cmp uc reverse($_[1]) }, 'ci-d' => sub { uc $_[1] cmp uc $_[0] }, 'ci-d-r' => sub { uc reverse($_[1]) cmp uc reverse($_[0]) }, 'n-a' => sub { $_[0] <=> $_[1] }, 'n-d' => sub { $_[1] <=> $_[0] }, 'l-a' => sub { length($_[0]) <=> length($_[1]) }, 'l-d' => sub { length($_[1]) <=> length($_[0]) }, ); return $sorts{$type}->($a,$b) if $type; my $random_sort = (keys %sorts)[rand (keys %sorts)]; return $sorts{$random_sort}->($a,$b) if !$type; }

It is used as follows.

my @unsorted_array = qw(red yellow green cyan blue magenta); my @sorted_array = sort { short_sorts($a,$b,'ci-d-r") } @unsorted_arra +y; print "$_\n" for @sorted_array;

That will return the list case insensitively sorted in descending order with the values read in reverse (right to left).

yellow green cyan blue red magenta

This is just another snippet from my small collection of odd subroutines floating about my hard drive. There are two things: I am not sure that I like the hyphens, and can this be expanded further?

Have a cookie and a very nice day!
Lady Aleena