in reply to Sorting Hash: Sort Criteria Moved Into Eval
You're evaling the code on every execution of the sort block — that's terribly inefficient. Try something like this:
my $sortCriteria = '$hr->{$b}->{"number"} <=> $hr->{$a}->{"number"}'; my $sortfunc = eval "sub { $sortCriteria }'; @sortedKeys = sort $sortfunc keys %$hr;
That compiles the code just once, puts it in an anonymous function, and stores a reference to that function in $sortfunc. sort then simply calls upon this already-compiled function to compare two values.
Wrapping evaled expressions in a sub { } like that is usually advisable when you're want to run the code passed in the string in a loop.
Makeshifts last the longest.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Sorting Hash: Sort Criteria Moved Into Eval
by aanhouden (Novice) on Jul 07, 2009 at 11:39 UTC |