I haven't had to do "special" sorts very often and I was quite pleased with the end result on this one- I think it is the most readable/understandable, whilst eliminating testing for the same thing (or it's negation) more than once and the temporary variable. I am sure some (or all) of the steps could have been skipped with experience, the answer looks obvious to me now but wasn't at the beginning.
# sort things containing a colon after things without # fist attempt if ( $a =~ /:/ ){ return $a cmp $b if $b =~ /:/; return 1; } if ( $b =~ /:/ ){ return -1; } $a cmp $b; # version 2, only one $a cmp $b return 1 if ( $a =~ /:/ and $b !~ /:/ ); return -1 if ( $b =~ /:/ and $a !~ /:/ ); $a cmp $b; # version 3 with input from a colleague, only apply a re to # each var once now if ( my $x = ($a =~ /:/) <=> ($b =~ /:/) ){ return $x; } $a cmp $b; # maybe better maybe not but it allowed me to see the # final option- my $x = ($a =~ /:/) <=> ($b =~ /:/); $x ? $x : $a cmp $b; # a good nights sleep and... (($a =~ /:/) <=> ($b =~ /:/)) || $a cmp $b;
--
Do not seek to follow in the footsteps of the wise. Seek what they sought. -Basho
In reply to Genesis of a sort routine by greenFox
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |