[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: function lookups, just like method lookups! (was Re: [FWP]alien method calls)



On Tue, 25 Apr 2000, Jeff Pinyan wrote:

> The basic gist is that it catches function calls from a package that
> aren't defined, and traverses the ISA tree -- it's the method call lookup
> for function calls.

You can also use the 'can' method to look up a subroutine as well as a
method:

    (B->can($_) or next)->() for qw/alpha woof gamma/;
    (C->can($_) or next)->() for qw/alpha bravo charlie/;

The following &AUTOLOAD is roughly equivalent to the original.  I had to
reference the non-existent missing function ($pkg = \&$AUTOLOAD) to get it
working (it goes into some sort of recursion otherwise).  Anyone know why?

  #!/usr/bin/perl -w

  no warnings qw/deprecated/;  # My first use of 'warnings' pragma :)

  package UNIVERSAL;
  $DEBUG = 1;
  sub AUTOLOAD {
    if ($DEBUG) {
      my ($file,$line) = (caller)[1,2];
      print STDERR "&$AUTOLOAD called at $file line $line\n";
    }
    my ($pkg,$func) = $AUTOLOAD =~ /(.*)::(.*)/;
    if ($func = $pkg->can($func)) {
      no strict;
      $pkg = \&$AUTOLOAD;  # Can anyone exlain why this is needed?
      *$AUTOLOAD = $func;
      goto &$AUTOLOAD;
    }
    require Carp;
    Carp::croak("Undefined subroutine &$AUTOLOAD called");
  }

>   package A;
>   sub alpha { print 1, "@_" }
>   sub beta { print 2 }
>   sub gamma { print 3 }
> 
>   package B;
>   @ISA = qw( A );
>   sub bravo { print 5 }
>   sub charlie { print 6 }
>   alpha(),bravo(),gamma();
> 
>   package C;
>   @ISA = qw( B );
>   alpha(),bravo(),charlie();
> 
> 
> Maybe God did not intend for this sort of mayhem. :)

"Come, let us go down and there confuse their language, that they may not
understand one another's speech." -- Genesis 11:7

As you can see, it's God's intention that we program in Perl. :)

-- 
Neko







==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe