This is mostly for elegance in code than anything else, but can anybody optimize the following snippet of code?

my $cmp_shift = (($a cmp $b) * ($top cmp $a) * ($top cmp $b)) || (($top eq $b) <=> ($top eq $a));

I'm not sure if there's some sort of rules involving algebraic simplification of comparitive operators, but it would be a nice thing to know in this case. Converting comparitive statements to variables and trying multiplicative simplification doesn't yield anything. I'm pretty good with logic, but not to this degree.

The overall goal on this sort function was to have a forced starting value, and have everything before the starter to be appended to the end. Like, if J was the starter and the values was A-N, the list would be JKLMNOABCDEFGHI.

The first part of the code (before the ||) works well except if the starter actually popped in as $a or $b. Hence, it checks for a zero and the right side of the OR fixes that.

This seems overly complex and messy, but I wanted to see if I could get it down to a single logic/comparison formula. Here's the entire test code, with debug data:

@unsort = sort { int(rand(3)) - 1 } ('aaa','yyy','fff','bbb','eee','dd +d','fff','jjj','iii','kkk','zzz','xxx','vvv','sss'); print "T\tA\tB\tA<>B\tT<>A\tT<>B\tTA<>TB\tRESULT\n"; @sort = sort { &sort_alpha_wrap('jjj',$a,$b); } @unsort; print join("\n", @sort)."\n"; sub sort_alpha_wrap { my ($top, $a, $b) = @_; my $cmp_shift = (($a cmp $b) * ($top cmp $a) * ($top cmp $b)) || (( +$top eq $b) <=> ($top eq $a)); print "$top\t$a\t$b\t".($a cmp $b)."\t".($top cmp $a)."\t".($top cm +p $b)."\t".(($top eq $b) <=> ($top eq $a))."\t$cmp_shift\n"; return $cmp_shift; }

In reply to Optimizing a sort function (wrap-around alpha) by SineSwiper

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.