Re: How to define a sub on the fly?
From: Anno Siegel (anno4000_at_lublin.zrz.tu-berlin.de)
Date: 05/01/04
- Next message: kj: "Re: How to define a sub on the fly?"
- Previous message: Peter Scott: "Re: How to define a sub on the fly?"
- In reply to: Mark Clements: "Re: How to define a sub on the fly?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 1 May 2004 12:40:10 GMT
Mark Clements <mark.clements@kcl.ac.uk> wrote in comp.lang.perl.misc:
> Anno Siegel wrote:
>
> >>eval<<EOF;
> >> sub newsub(){
> >
> >
> > Why the prototype? They are the exception with sub definitions, not
> > the rule.
> I tend to use them because if used correctly they enable the compiler to
> catch attempts to call subs with the wrong number of arguments,
True, but it also makes your subs behave weirdly, supplying unexpected
context to arguments or even silently taking references. In my view,
prototypes can (sparingly) be used in interface-type functions to
help the user deal with them, or to allow suggestive syntax. The
non-standard behavior must be clearly documented. Few Perl programmers
use prototypes routinely with all subs.
> though
> obviously here they'll have no effect as the compiler can't see the
> definition of the new sub. It was therefore misleading of me to use it here.
>
>
> >
> > *newsub = sub { return "from newsub" };
> In this case, yes, but I don't see how this enables you to build
> subroutines on the fly. eval STRING is relatively inefficient but
> extremely powerful (and therefore dangerous).
If you actually need to compile a string of code for the new sub, there
is no way around "eval".
Often a closure gives enough flexibility. If the sub needs to read a
particular file, this would do (simplified, untested):
sub create_sub {
my $name = shift;
my $sub = sub {
open( my $f, $name) or die "Can't read file '$name': $!";
# ...
};
no strict 'refs';
*{ 'read_' . $name} = $sub;
}
That creates one named closure per call, each reading the file it is
named after. No need for "eval" here.
Anno
- Next message: kj: "Re: How to define a sub on the fly?"
- Previous message: Peter Scott: "Re: How to define a sub on the fly?"
- In reply to: Mark Clements: "Re: How to define a sub on the fly?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|