in reply to Sorting Hash: Sort Criteria Moved Into Eval

mdog,
Have you considered using Tie::Hash::Sorted? It allows you to dynamically change the sort routine which it seems you want to do. Additionally, it allows you to modify the hash arbitrarily and still maintain its "sortedness".
#!/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
    Many, many thanks to all of you...When my script doesn't run the way I want it to, I think there is a problem with what I have done, not that Perl has a bug in it! :)

    Aristotle, I will definitely move the eval out so that it only compiles once and Limbic~Region, I'll investigate Tie::Hash::Sorted as it looks very interesting!

    mdog