in reply to AUTOLOAD functions & inheritence

Kinda messy. I know there's a better way to do it, but I don't have the reference book with me. Here's what I came up with:
package A; sub bar { return "BAR"; } sub AUTOLOAD { my (@objpath) = split(/::/, $AUTOLOAD); my $fname = pop @objpath; return if $fname eq 'DESTROY'; if ( $fname eq 'baz' ) { my $subr = <<EOSUB; sub $AUTOLOAD { return "FOO"; } EOSUB eval $subr; goto &$AUTOLOAD; return $subr; } return; } package B; @ISA = qw( A ); sub new { return bless {}, shift; } sub AUTOLOAD { my (@objpath) = split(/::/, $AUTOLOAD); my $fname = pop @objpath; return if $fname eq 'DESTROY'; if ( $fname eq 'foo' ) { my $subr = <<EOSUB; sub $AUTOLOAD { return "FOO"; } EOSUB eval $subr; goto &$AUTOLOAD; } else { return &{"A::$fname"}; } return; } package main; my $b = new B; print "foo: ", $b->foo, "\n"; print "bar: ", $b->bar, "\n"; print "baz: ", $b->baz, "\n";
The biggest change I made was adding an else clause to B::AUTOLOAD(). If the appropriate subroutine isn't found in package B, it constructs a symbolic reference to a function in A. Since that function may not be there, it's trapped by AUTOLOAD.

I have no idea whether or not this gets caching, but I'll check. It's not very clean or elegant or safe, so I wouldn't use it except in an emergency. Still, it's One Way To Do It.

Replies are listed 'Best First'.
RE: Re: AUTOLOAD functions & inheritence
by Anonymous Monk on Mar 30, 2000 at 02:55 UTC
    I tried to do a simmilar thing with SUPER::.
    if ( handle this ) { eval "sub $AUTOLOAD {}"; goto &$AUTOLOAD } else { goto &{"SUPER::$fname"}; }
    I didn't want to presume which parent function to call. -Sean.
      I tried to do a simmilar thing with SUPER::.

      if ( handle this ) { eval "sub $AUTOLOAD {...}"; goto &$AUTOLOAD } else { goto &{"SUPER::$fname"}; }

      I didn't want to presume which parent function to call.


       
      -Sean.