On 9/13/07, lists user <[EMAIL PROTECTED]> wrote:
> Hello,
>
> Why we need AUTOLOAD and what's the usage of $AUTOLOAD?
> Can you show an example to help explain it?Thanks in advance.
snip

The AUTOLOAD subroutine is what Perl runs if it can't find the
function you have requested.  $AUTOLOAD is a package variable (aka an
our variable) that is holds the name of the subroutine the program
tried to run but could not find.  It is fully qualified, so if the
package is Foo::Bar and the subroutine is baz then $AUTOLOAD would be
Foo::Bar::baz.

There are at least two reasons to use AUTOLOAD:

1. to defer loading of subroutines until they are needed (efficiency)

Say you have a module Foo.  In Foo there are thousands of function
definitions.  Your script only uses five of them on average, but there
are some corner cases where you will need all of them.  You also need
the script to run as quickly as possible.  Your script will waste time
parsing and compiling the thousands of subroutines you mostly won't
use.  What can you do?  Well, one solution is to use AUTOLOAD (this is
what AutoLoader and AutoSplit do).  You can keep the five commonly
used functions in the main module and create submodules for individual
functions (or groups of functions).  When a function is called that
hasn't been loaded yet, AUTOLOAD will run and can load the submodule
with the function definition, and then call the function returning its
result as if nothing special had happened.

2. to avoid defining common subroutines (Laziness)

Say you are writing some code and notice that you have several
functions that are identical or nearly identical (this happens with
getter/setter functions in OO a lot).  You could write all of that
code or you could write one subroutine (AUTOLOAD) that can do
everything:


#!/usr/bin/perl

use strict;
use warnings;

my $foo = Foo->new(1,2);

print join(", ", $foo->foo, $foo->bar, $foo->baz), "\n";

$foo->baz(3);

print join(", ", $foo->foo, $foo->bar, $foo->baz), "\n";

package Foo;

BEGIN {
        our $AUTOLOAD;
        our @fields = qw<foo bar baz>;
}

sub new {
        our @fields;
        my $class = shift;
        my %self;
        @[EMAIL PROTECTED] = (@_, (0) x @fields);
        return bless \%self, $class;
}

sub AUTOLOAD {
        our ($AUTOLOAD, @fields);
        my $self = shift;
        my $sub = (split '::', $AUTOLOAD)[-1];
        return if $sub eq 'DESTROY';
        die "$sub not defined" unless grep { $sub eq $_ } @fields;

        #if there were args, then this is a setter
        $self->{$sub} = shift if @_;

        return $self->{$sub};
}

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to