mdog has asked for the wisdom of the Perl Monks concerning the following question:
I want to sort a multidimensional hash by one of it's values and want to be able to build the sort criteria on the fly. I can get this to work fine if it isn't in a subroutine but as soon as I do this in a sub (passing the hash by reference), I start getting wacky results.
I am including the code I have been using to test and wondering what I am doing wrong.
Many thanks in advance,
mdog
$hash{'Me'}->{"name"} = "Me"; $hash{'Me'}->{"number"} = "7.7"; $hash{'Chuck'}->{"name"} = "Chuck"; $hash{'Chuck'}->{"number"} = "7.7"; $hash{'Zed'}->{"name"} = "Zed"; $hash{'Zed'}->{"number"} = "7.7"; $hash{'Wife'}->{"name"} = "Wife"; $hash{'Wife'}->{"number"} = "7.6"; $hash{'Dad'}->{"name"} = "Dad"; $hash{'Dad'}->{"number"} = "53"; $hash{'Michael'}->{"name"} = "Michael"; $hash{'Michael'}->{"number"} = "24"; test(\%hash); sub test{ my($hr) = @_; # sort criteria embedded: expected results @sortedKeys = sort { $hr->{$b}->{"number"} <=> $hr->{$a}->{"number +"} } keys %$hr; print "sort criteria embedded\n"; foreach my $sortedKey(@sortedKeys){ print $hr->{$sortedKey}->{"number"} . " " . $hr->{$sortedKey}- +>{'name'} . "\n"; } # sort criteria eval-ed: wacky results my $sortCriteria = '$hr->{$b}->{"number"} <=> $hr->{$a}->{"number" +}'; # WHAT AM I DOING WRONG ON THE NEXT LINE? @sortedKeys = sort { eval $sortCriteria } keys %$hr; print "\n\nsort criteria eval-ed\n"; foreach my $sortedKey(@sortedKeys){ print $hr->{$sortedKey}->{"number"} . " " . $hr->{$sortedKey}- +>{'name'} . "\n"; } }
The results:
sort criteria embedded 53 Dad 24 Michael 7.7 Me 7.7 Zed 7.7 Chuck 7.6 Wife sort criteria eval-ed 53 Dad 7.6 Wife 7.7 Me 7.7 Zed 24 Michael 7.7 Chuck
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Sorting Hash: Sort Criteria Moved Into Eval
by keszler (Priest) on Aug 06, 2004 at 00:53 UTC | |
|
Re: Sorting Hash: Sort Criteria Moved Into Eval
by BrowserUk (Patriarch) on Aug 06, 2004 at 01:33 UTC | |
|
Re: Sorting Hash: Sort Criteria Moved Into Eval
by davido (Cardinal) on Aug 06, 2004 at 02:13 UTC | |
|
Re: Sorting Hash: Sort Criteria Moved Into Eval
by Aristotle (Chancellor) on Aug 06, 2004 at 02:33 UTC | |
by aanhouden (Novice) on Jul 07, 2009 at 11:39 UTC | |
|
Re: Sorting Hash: Sort Criteria Moved Into Eval
by Limbic~Region (Chancellor) on Aug 06, 2004 at 13:09 UTC | |
by mdog (Pilgrim) on Aug 06, 2004 at 16:32 UTC |