in reply to Fun with complex sorting on arbitrary criteria list.
One suggestion for your code, use eval's return value to create an sub rather than evaling the whole sort routine. Here is a quick example of the technique.
This way you can re-use your sort routine without the eval penalty again.my $test = eval "sub { print 'hello world' }"; $test->(); # prints the ever-classic "hello world"
Regarding similar sorting techniques. I usually, like tilly, have used closures (although using closures somewhat differently than tilly).
I have not tried to eval a code string for this problem though, personally i was never a huge fan of that technique, although your example is a quite an interesting use of it. Cool stuff. -stvnmy %hash = ( 'Lisa' => [ 'F', 6, 150, 'Blonde', 'Blue' ], 'Homer' => [ 'M', 40, 105, 'Bald', 'Blue' ], 'Bart' => [ 'M', 9, 120, 'Blonde', 'Brown' ], 'Marge' => [ 'F', 36, 135, 'Blue', 'Blue' ], 'Maggie' => [ 'F', 1, 130, 'Blonde', 'Blue' ] ); sub createSortRoutine { my (@ordered_values) = @_; return sub { my ($left, $right) = @_; my $result; foreach (@ordered_values) { $result = ( ($hash{$left}->[$_] =~ /^\d+$/) ? $hash{$left}->[$_] <=> $hash{$right}->[$_] : $hash{$left}->[$_] cmp $hash{$right}->[$_] ) unless $result; } return $result; }; } my $sorter = createSortRoutine(0, 2, 3); print join "\n" => sort { $sorter->($a, $b) } keys %hash; # NOTE: this code not thoroughly tested, i lifted it from # and old module of mine and hacked it for this example. __DATA__ Maggie Marge Lisa Homer Bart
|
|---|