in reply to sort a hash with split values

You may want to look at Schwartzian Transform:
my @sorted_keys = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [ $_, (split/:/,$hash{$_})[1] ] } keys $hash;
_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

Replies are listed 'Best First'.
Re^2: sort a hash with split values
by Anonymous Monk on Jun 21, 2006 at 18:14 UTC
    Hi. that worked great! Now I don't understand all that code so I'm playing with it. I want to now sort on the THIRD delimited data. I changed all of the 1s in there to 2s and it doesn't appear to be working. Need I change something else?
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re^2: sort a hash with split values
by derby (Abbot) on Jun 21, 2006 at 19:21 UTC

    Never been a big fan of ST ... it's kinda like a one night stand ... sure it feels good but you feel ashamed afterwards (or so I'm told). Just use temp variables ...

    #!/usr/bin/perl use strict; use warnings; my %hash = ( 'foo00' => '12:NY:me@yoi00.com', 'foo01' => '12:NJ:me@yoi01.com', 'foo02' => '12:NV:me@yoi02.com', 'foo03' => '12:AL:me@yoi03.com', 'foo04' => '12:AK:me@yoi04.com', 'foo05' => '12:MD:me@yoi05.com', 'foo06' => '12:MO:me@yoi06.com', 'foo07' => '12:MI:me@yoi07.com', 'foo08' => '12:MA:me@yoi08.com', 'foo09' => '12:CA:me@yoi09.com', ); # create array that looks like this # [ # [ foo00, NY ], # [ foo01, NJ ], # .. # [ foo09, CA ] # ] my @temp; foreach my $key ( keys %hash ) { my @values = split( /:/, $hash{$key} ); push( @temp, [ $key, $values[1] ] ); } # sort array by second element my @sort = sort { $a->[1] cmp $b->[1] } @temp; # roll through sort and use # first element of array as key into hash foreach my $ref ( @sort ) { print "$ref->[0]: $hash{$ref->[0]}\n"; }
    So ST is compact but too dense for me (or maybe I'm too dense for ST).

    -derby