in reply to Re: How do I create a sort sub on-the-fly?
in thread How do I create a sort sub on-the-fly?
No need to be ashamed of the eval, it's a standard technique in happy programs (who said "programs that generate other programs are the happiest programs of all"?).
For a simple case like ascending/descending you can just generate the coderef at once:
sub sortmaker { my $order = shift; my $sub = $order ? sub { $a <=> $b } : sub {$b <=> $a}; return $sub; }
but if you need to build the subroutine then eval is the way to go. I would write it a little more verbosely though:
sub sortmaker { my $order = shift; my $clause = $order ? '$a <=> $b' : '$b <=> $a'; my $sub= eval "sub { $clause}"; # create the coderef return $sub; # explicitely return it }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re (tilly) 3: How do I create a sort sub on-the-fly?
by tilly (Archbishop) on Nov 02, 2001 at 18:41 UTC | |
Re: Re: Re: How do I create a sort sub on-the-fly?
by CharlesClarkson (Curate) on Nov 06, 2001 at 11:12 UTC |
In Section
Seekers of Perl Wisdom