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 }
In reply to Re: Re: How do I create a sort sub on-the-fly?
by mirod
in thread How do I create a sort sub on-the-fly?
by CharlesClarkson
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |