Rick Triplett wrote:
> 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

You need a Schwartzian transform.  It works by extract the sort fields
from the data and placing them, and the original data, in an array of
arrays (AoA).  It sorts the AoA and extracts the original data from
them.  This sorted list now can be used.


#!/usr/bin/env perl

use strict;
use warnings;

use Data::Dumper;

# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent   = 1;

# Set maximum depth for Data::Dumper, zero means unlimited
$Data::Dumper::Maxdepth = 0;

# example hash
my %answers = (
  '1' => 'b',
  '2h' => 'c',
  3 => 'a',
  2 => 'a',
);

# create an array of arrays with the fields extracted from the keys
my @aoa = map { [ $_, m{ \A (\d+) (.*) }msx ] } keys %answers;
print '@aoa = ', Dumper \...@aoa;

# sort the array of arrays
my @sorted_aoa = sort { $a->[1] <=> $b->[1] || $a->[2] cmp $b->[2] ||
$a->[0] cmp $b->[0] } @aoa;
print '@sorted_aoa = ', Dumper \...@sorted_aoa;

# extract the keys
my @sorted_keys = map { $_->[0] } @sorted_aoa;
print '@sorted_keys = ', Dumper \...@sorted_keys;

# display
print '-' x 40, "\n";
for my $key ( @sorted_keys ){
  printf "%5s: %s\n", $key, $answers{$key};
}

# putting everything together
print '-' x 40, "\n";
for my $key ( map { $_->[0] }
              sort { $a->[1] <=> $b->[1] || $a->[2] cmp $b->[2] ||
$a->[0] cmp $b->[0] }
              map { [ $_, m{ \A (\d+) (.*) }msx ] }
              keys %answers;
){
  printf "%5s: %s\n", $key, $answers{$key};
}


-- 
Just my 0.00000002 million dollars worth,
  Shawn

Programming is as much about organization and communication
as it is about coding.

I like Perl; it's the only language where you can bless your
thingy.

-- 
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