>-----Original Message-----
>From: Rick Triplett [mailto:r...@reason.net]
>Sent: Tuesday, October 13, 2009 12:09 PM
>To: Perl Beginners
>Subject: Sorting mixed alphanumerics
>
>I need to sort the keys in a hash. The keys are the question number
>and the values are the student's answer. A numeric sort with <=> won't
>work since retaking a missed question (say, 2) produces the new key,
>2h with its new answer. A representative hash might look like this
>
>1 => b
>2h => c
>3 => a
>2 => a
>
>I chose the sort routine
>
>{$a <=> $b || $a cmp $b}
>
>which sorts correctly but gives me a warning about the occasional "h"
>not being numeric. I could suppress warnings for the sort routine or
>for the whole code, but I'd rather write better code, code that
>doesn't produce a warning. Unfortunately I haven't been able to figure
>out the correct code, despite looking through the sort sections of the
>standard books on Perl. Even though I'm a Perl novice, my intuition
>tells me that there is probably a simple way to do this. But several
>days of experimenting have been unsuccessful.
>

I don't know if this is the simple way.

http://www.stonehenge.com/merlyn/UnixReview/col64.html
http://en.wikipedia.org/wiki/Schwartzian_transform

use strict;
use warnings;
my %results = ( '1' => 'b', '2h' => 'c', '3' => 'a', '2' => 'a', );
print "question $_ answer $results{$_}\n"
    for map { $_->[0] }
    sort { $a->[1] <=> $b->[1] || $a->[2] cmp $b->[2] }
    map { [ $_, /^(\d+)(\D+|$)/ ] } keys %results;

question 1 answer b
question 2 answer a
question 2h answer c
question 3 answer a

>Advice appreciated!
>
>Rick Triplett
>
>--
>To unsubscribe, e-mail: beginners-unsubscr...@perl.org
>For additional commands, e-mail: beginners-h...@perl.org
>http://learn.perl.org/
>


Regards,
 
Scott Hall
Columbia MEIS
Bose Corporation

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to