|
Posted by Ronny on April 8, 2008, 9:58 am
Please log in for more thread options > On Mon, 07 Apr 2008 20:55:32 +0000, Uri Guttman wrote:
> > it is just a wacko way to define a sub. it puts a code ref (the anon
> > sub) into the code slot in the *myname typeglob. it makes no sense to do
> > that unless the sub name was generated on the fly.
> I beg to differ. I do this frequently to populate a class with a
> number of similar methods, e.g.:
>
> use Log::Log4Perl;
> BEGIN {
> for my $method ( keys %Log::Log4perl::Level::PRIORITY ) {
> no strict 'refs';
> *$method = sub {
> my $self = shift;
> my $logger = Log::Log4Perl->get_logger( ref $self );
> $logger->$method( @_ );
> }
> };
>
> }
Well, your case *does* make sense, because $method is a different
string on every execution. My original example, however, was that
the method name was "constant" (i.e. set to the same string on every
execution), so I agree with Uri that this could have done more
naturally
in the conventional way of defineing a sub.
Ronald
>
> Or there's just-in-time method creation (traditional objects):
>
> sub AUTOLOAD {
> (my $method = our $AUTOLOAD) =~ s/.*://;
> return if $method eq 'DESTROY';
> croak "No such attribute" unless $ALLOWED_ATTR;
> no strict 'refs';
> *$method = sub {
> my $self = shift;
> $self-> = shift if @_;
> return $self->;
> };
> goto &$method;
>
> }
>
> I don't think a dispatch table is a better solution for those cases.
>
> --
> Peter Scotthttp://www.perlmedic.com/http://www.perldebugged.com/
|