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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: short sorts
by GrandFather (Saint) on Mar 28, 2012 at 10:12 UTC | |
Re: short sorts
by tobyink (Canon) on Mar 28, 2012 at 10:20 UTC | |
by Lady_Aleena (Priest) on Mar 30, 2012 at 17:26 UTC | |
Re: short sorts
by tobyink (Canon) on Mar 28, 2012 at 11:07 UTC | |
Re: short sorts
by choroba (Cardinal) on Mar 28, 2012 at 11:40 UTC | |
by Lady_Aleena (Priest) on Mar 30, 2012 at 17:23 UTC | |
Re: short sorts
by Arunbear (Prior) on Mar 30, 2012 at 14:48 UTC | |
by Lady_Aleena (Priest) on Mar 30, 2012 at 18:39 UTC | |
by Arunbear (Prior) on Apr 03, 2012 at 17:49 UTC | |
by Lady_Aleena (Priest) on Apr 06, 2012 at 20:43 UTC | |
by Arunbear (Prior) on Apr 07, 2012 at 15:37 UTC | |
|
Back to
Cool Uses for Perl