<?xml version="1.0" encoding="windows-1252"?>
<node id="962078" title="short sorts" created="2012-03-28 01:52:18" updated="2012-03-28 01:52:18">
<type id="1042">
CUFP</type>
<author id="161890">
Lady_Aleena</author>
<data>
<field name="doctext">
&lt;p&gt;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.&lt;/p&gt;
&lt;code&gt;
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'   =&gt; sub { $_[0] cmp $_[1] },
    'cs-a-r' =&gt; sub { reverse($_[0]) cmp reverse($_[1]) },
    'cs-d'   =&gt; sub { $_[1] cmp $_[0] },
    'cs-d-r' =&gt; sub { reverse($_[1]) cmp reverse($_[0]) },
    'ci-a'   =&gt; sub { uc $_[0] cmp uc $_[1] },
    'ci-a-r' =&gt; sub { uc reverse($_[0]) cmp uc reverse($_[1]) },
    'ci-d'   =&gt; sub { uc $_[1] cmp uc $_[0] },
    'ci-d-r' =&gt; sub { uc reverse($_[1]) cmp uc reverse($_[0]) },
    'n-a'    =&gt; sub { $_[0] &lt;=&gt; $_[1] },
    'n-d'    =&gt; sub { $_[1] &lt;=&gt; $_[0] },
    'l-a'    =&gt; sub { length($_[0]) &lt;=&gt; length($_[1]) },
    'l-d'    =&gt; sub { length($_[1]) &lt;=&gt; length($_[0]) },
  );
  
  return $sorts{$type}-&gt;($a,$b) if $type;
  
  my $random_sort = (keys %sorts)[rand (keys %sorts)];
  return $sorts{$random_sort}-&gt;($a,$b) if !$type;
}
&lt;/code&gt;
&lt;p&gt;It is used as follows.&lt;/p&gt;
&lt;code&gt;
my @unsorted_array = qw(red yellow green cyan blue magenta);

my @sorted_array = sort { short_sorts($a,$b,'ci-d-r") } @unsorted_array;

print "$_\n" for @sorted_array;
&lt;/code&gt;
&lt;p&gt;That will return the list case insensitively sorted in descending order with the values read in reverse (right to left).&lt;/p&gt;
&lt;code&gt;
yellow
green
cyan
blue
red
magenta
&lt;/code&gt;
&lt;p&gt;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?&lt;/p&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-161890"&gt;
&lt;div&gt;&lt;strong&gt;&lt;em&gt;Have a cookie and a very nice day!&lt;/em&gt;&lt;/strong&gt;&lt;/div&gt;
&lt;div&gt;&lt;em&gt;Lady Aleena&lt;/em&gt;&lt;/div&gt;
&lt;/div&gt;&lt;/div&gt;</field>
</data>
</node>
