"be consistent" PerlMonks

### Re: Numeric Sorting on Characters

by johngg (Abbot)
 on Aug 14, 2013 at 21:31 UTC ( #1049484=note: print w/replies, xml ) Need Help??

in reply to Numeric Sorting on Characters

Another way is to use a Schwartzian Transform passing the key, an indicator whether the cpu is "-" (1 - TRUE or 0 - FALSE) and the cpu value in an array ref. Sorting can then be done on the indicator first then on cpu value but the second sort term is a ternary so that comparing two items with a "-" cpu value immediately returns zero.

\$ perl -Mstrict -Mwarnings -E ' my \$passes = { t1 => { cpu => 73, xx => 3 }, t2 => { cpu => q{-}, xx => 7 }, t3 => { cpu => 17, xx => 0 }, t4 => { cpu => 49, xx => 6 }, t5 => { cpu => q{-}, xx => 4 }, t6 => { cpu => 11, xx => 5 }, }; say for map { \$_->[ 0 ] } sort { \$a->[ 1 ] <=> \$b->[ 1 ] || ( \$a->[ 1 ] ? 0 : \$a->[ 2 ] <=> \$b->[ 2 ] ) } map { [ \$_, \$passes->{ \$_ }->{ cpu } eq q{-}, \$passes->{ \$_ }->{ cpu }, ] } keys %\$passes;' t6 t3 t4 t1 t2 t5 \$

I hope this is of interest.

Update: Ignore this, it doesn't seem to be sorting correctly :-(

Update 2: I was bitten on the bum by a silly precedence problem that should have occurred to me sooner. Replacing

sort { \$a->[ 1 ] <=> \$b->[ 1 ] || \$a->[ 1 ] ? 0 : \$a->[ 2 ] <=> \$b->[ 2 ] }

with

sort { \$a->[ 1 ] <=> \$b->[ 1 ] || ( \$a->[ 1 ] ? 0 : \$a->[ 2 ] <=> \$b->[ 2 ] ) }

solved the problem.

Cheers,

JohnGG

Log In?
 Username: Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1049484]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2018-03-25 03:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When I think of a mole I think of:

Results (300 votes). Check out past polls.

Notices?