On Wed, Jul 8, 2009 at 15:09, "Alexander
Müller"<alexan.muel...@fh-wolfenbuettel.de> wrote:
> Hi,
>
> I need an order for hash by user preferences. Because the criterion to order 
> the hash entries a not numerical and not should sorted alphabetical, I tried 
> following
>
>
>   3 %hashToSort = (
>   4     "a" => "one",
>   5     "b" => "two",
>   6     "c" => "three",
>   7 );
>
> @keys = sort { qw(a, b, c) } (keys %hashToSort);
>  16     foreach $key (@keys) {
>  17         print "$key -> $hashToSort{$key}";
>  18         print "\n\n";
>  19     }
>
> but this didn't work.
>
> The criterion are string entries of the hash keys.
snip

You need to map the hash keys to something that is sortable:

#!/usr/bin/perl

use strict;
use warnings;

my %hash = (
        name => "foo",
        dob  => "2009-07-08",
        sex  => "M",
);

my %sort_order = (
        sex  => "1",
        name => "2",
        dob  => "3",
);

for my $key (sort { $sort_order{$a} <=> $sort_order{$b} } keys %hash) {
        print "$key => $hash{$key}\n";
}


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

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