http://qs1969.pair.com?node_id=553767


in reply to Creating packages on the fly

I'm not entirely sure that what I am about to suggest is very sensible as it may well break all sorts of other things, so anyone of a sensitive nature should look away now.

It is entirely possible to add an AUTOLOAD subroutine to the UNIVERSAL package which every other package inherits from implicity, so you can do something like:

#!/usr.bin/perl use strict; use warnings; Foo::Bar->baz(); Foo::Bar->baz(); package UNIVERSAL; sub AUTOLOAD { my ($class, @args) = @_; our $AUTOLOAD; (my $method = $AUTOLOAD) =~ s/.*:://; print "$AUTOLOAD was called via autoload\n"; no strict 'refs'; *{$AUTOLOAD} = sub { print "I'm alive\n"}; $class->$method; }
This creates your methods in unknown packages on the fly. If you want to do subclassing on the fly you can do something like:
#!/usr.bin/perl use strict; use warnings; Foo::Bar->baz(); Foo::Bar->baz(); package UNIVERSAL; sub AUTOLOAD { my ($class, @args) = @_; our $AUTOLOAD; (my $method = $AUTOLOAD) =~ s/.*:://; (my $parent = $class) =~ s/::[^:]*$//; print "$AUTOLOAD was called via autoload\n"; no strict 'refs'; push @{"${class}::ISA"},$parent; $class->$method; } package Foo; sub baz { my ($self) = @_; print "I'm alive\n"; }

But don't say I didn't warn you that this was probably a bad idea

/J\

Replies are listed 'Best First'.
Re^2: Creating packages on the fly
by Jouke (Curate) on Jun 06, 2006 at 09:16 UTC
    First of all, thanks! This is indeed what I want to achieve. The UNIVERSAL::AUTOLOAD sub will of course do more checking than just this to implement what I want.

    However, like you said, this may not be a good idea. What if more people start using this scheme? Then things will break immediately. I'm pretty sure I can catch that by checking if UNIVERSAL::AUTOLOAD has already been defined (right?).

    nevertheless this may just be the push in the right direction I need


    Jouke Visser
    Using Perl to enable the disabled: pVoice

      Yeah, I can't see any reason why you couldn't (say in the import() of the module that defines this) save any existing UNIVERSAL::AUTOLOAD and then call that at some point in your version, of course you might be stuffed if (as some more normal AUTOLOAD subroutines do) it does goto &{$AUTOLOAD};. However I don't actually know of anything that uses this hack in the wild.

      /J\

Re^2: Creating packages on the fly
by DrHyde (Prior) on Jun 06, 2006 at 09:07 UTC
    Dear sir,

    you are evil sick and wrong. That's why I love you.

    Hugs n kisses

    Dave