← Back to Perl Course | Chapter 7: Object-Oriented Perl | Lesson 7 of 7

AUTOLOAD and DESTROY

AUTOLOAD catches calls to methods that do not exist, and DESTROY runs when an object is cleaned up.

In this page:

  1. AUTOLOAD and DESTROY

AUTOLOAD and DESTROY

When a method is not found, Perl looks for a subroutine named AUTOLOAD in the class hierarchy and sets the package variable $AUTOLOAD to the full name of the missing method. You should return early for DESTROY, since Perl also calls DESTROY through AUTOLOAD if none is defined. DESTROY is called automatically when the last reference to an object goes away, which is useful for cleanup.

Note: Define an empty sub DESTROY {} if you use AUTOLOAD, so that object destruction does not go through AUTOLOAD.

Example: AUTOLOAD and DESTROY

perl
use strict;
use warnings;

package Flexible;
our $AUTOLOAD;

sub new { my $class = shift; return bless { color => "red", size => 5 }, $class; }

sub AUTOLOAD {
    my $self = shift;
    my $name = $AUTOLOAD;
    $name =~ s/.*:://;
    return if $name eq 'DESTROY';
    die "No method $name\n" unless exists $self->{$name};
    return $self->{$name};
}

package Tracked;
sub new { my ($class, $name) = @_; print "creating $name\n"; return bless { name => $name }, $class; }
sub DESTROY { my $self = shift; print "destroying $self->{name}\n"; }

package main;

my $f = Flexible->new;
print "color: ", $f->color, "\n";
print "size: ", $f->size, "\n";
eval { $f->weight };
print "error: $@";

{
    my $t = Tracked->new("temp");
    print "inside block\n";
}
print "after block\n";

# Output:
# color: red
# size: 5
# error: No method weight
# creating temp
# inside block
# destroying temp
# after block
Common Mistakes
  1. Forgetting to handle DESTROY inside AUTOLOAD
  2. Not stripping the package name from $AUTOLOAD
  3. Relying on the exact timing of DESTROY in cyclic data structures
Chapter Summary
  • AUTOLOAD handles missing methods
  • $AUTOLOAD holds the full method name
  • DESTROY runs when the last reference is gone
  • Define an empty DESTROY to avoid AUTOLOAD calls
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.