in reply to Re: Re: How do I create a sort sub on-the-fly?
in thread How do I create a sort sub on-the-fly?

I recommend against using a string eval without checking $@ and putting in an error check showing both the error and the generated code that produced that error. Else you could easily have a small typo and never know it, leading to much puzzling about why your sort worked strangely.

But luckily, even for complex sorts, you don't need eval. Instead for each specific clause you can build a function that takes that clause and produces a sort function from it. If you have multiple clauses, then you can combine them easily. Just walk through your clauses, building up an array of comparisons you want to do, and then call something like this:

# Takes a list of comparison subroutines for a sort, and # returns a combined comparison subroutine. sub combine_comp_subs { my @subs = @_; if (1 == @subs) { return shift @subs; } else { return sub { foreach my $sub (@subs) { my $c = $sub->(); return $c if $c; } return 0; }; } }
And now the main problem you have is figuring out how to set up your data structure to compare, and how to turn the individual conditions into individual sort subs. But you have the same problem with an eval solution...