AUTOLOAD allows dynamically handling calls to non-existing methods or functions in a package. This is convenient for creating proxy objects, dynamically generated methods (ORM), implementing lazy loading logic, etc.
AUTOLOAD:package MyAuto; sub AUTOLOAD { our $AUTOLOAD; my ($self, @args) = @_; my ($method) = $AUTOLOAD =~ /::(\w+)$/; print "Called $method with @args "; } package main; my $obj = bless {}, 'MyAuto'; $obj->any_method(1,2,3); # Will invoke AUTOLOAD
new, DESTROY.Question: Will AUTOLOAD be invoked if trying to call a non-existing constructor new?
Answer: No. Perl looks for the constructor new directly in the package and does not call AUTOLOAD for it if it's not found. AUTOLOAD is invoked only for regular method calls, not when trying to create an object via Class->new().
package Foo; sub AUTOLOAD { print "AUTOLOAD! "; } # $obj = Foo->new(); # Error: Can't locate object method "new" ...
Story In a cryptographic service, they implemented proxying for many similar methods through AUTOLOAD. They forgot to handle the situation with the DESTROY method, and when finalizing objects, infinite recursive calls occurred, causing the script to crash.
Story In an ORM, they used AUTOLOAD for magic field access, but did not implement correct value return when the method was actually absent. As a result, Perl issued a confusing message instead of "Can't locate...", with bugs appearing only in production.
Story During refactoring, they removed some actual methods, so all calls went through AUTOLOAD. This sharply decreased the performance of large tasks (processing an array of millions of objects became 10-15 times longer than before refactoring).