in reply to Sorting Hash: Sort Criteria Moved Into Eval
#!/usr/bin/perl use strict; use warnings; use Tie::Hash::Sorted; my $custom_sort = sub { my $h = shift; [ sort {$h->{$b}{number} <=> $h->{$a}{number}} keys %$h ]; }; tie my %hash, 'Tie::Hash::Sorted', 'Sort_Routine' => $custom_sort; my @keys = qw(name number); @{ $hash{$_} }{ @keys } = ($_, '7.7') for qw(Me Chuck Zed); @{ $hash{Wife} }{ @keys } = qw(Wife 7.6); @{ $hash{Dad} }{ @keys } = qw(Dad 53); @{ $hash{Michael} }{ @keys } = qw(Michael 24); print "$hash{$_}{number}\t$hash{$_}{name}\n" for keys %hash; @{ $hash{Foo} }{ @keys } = qw(foo 42); $custom_sort = sub { my $h = shift; [ sort {$h->{$a}{name} cmp $h->{$b}{name}} keys %$h ]; }; tied( %hash )->Sort_Routine( $custom_sort ); print "$hash{$_}{name}\t$hash{$_}{number}\n" for keys %hash;
Cheers - L~R
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Sorting Hash: Sort Criteria Moved Into Eval
by mdog (Pilgrim) on Aug 06, 2004 at 16:32 UTC |