Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks, I have a perl program which calls user-defined library pm files with predefined functions. Each user-defined library also contains:
sub AUTOLOAD { return undef; }
in case the user doesn't implement one of the functions, the library can still return an undef value for the unimplemented function. My question is this: how can my main program determine whether AUTOLOAD was called or an actual function exists that returned undef. Thanks a bunch, Michael

Replies are listed 'Best First'.
Re: AUTOLOAD question
by hardburn (Abbot) on Jun 11, 2003 at 14:15 UTC

    If you're being a good little OO programmer, you shouldn't care if the subroutine in question is coming out of AUTOLOAD or not.

    Now, Perl likes to break traditional rules (though you should know what the rules are and why they exist before you break them). You can use $object->can('meth') to check for this. can() will not return true for an AUTOLOAD method.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

      There is an exception to this.
      In your AUTOLOAD you can create an anonymous sub and install it in the symbol table by assigning to the typeglob for the value of $AUTOLOAD.
      Try this as a very simple example (read don't use in production as is)
      #! /usr/bin/perl -w use strict; print "NOT LOADED\n" unless FOO->can('bar'); FOO->bar(); print "NOW LOADED\n" if FOO->can('bar'); package FOO; use vars '$AUTOLOAD'; sub AUTOLOAD { no strict "refs"; my $class = shift; print "LOADING $AUTOLOAD\n"; *{$AUTOLOAD} = sub {print "USING CACHED VERSION";}; return }
      I guess I'm not a 'good little OO programmer' because these libraries are function-oriented rather than object-oriented, so iow I have no $object to use. btw, I can't seem to find any documentation on can()...Michael

        Even if you're not using an object system, you can still make use of OO concepts.

        can() is part of the UNIVERSAL class, which is the base for all objects in Perl. Even though you're not using the object system, you can still call it via PackageName->can('method').

        ----
        I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
        -- Schemer

        Note: All code is untested, unless otherwise stated