Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Strange code execution with 'AUTOLOAD'

by btrott (Parson)
on Jul 01, 2001 at 22:32 UTC ( #93045=note: print w/ replies, xml ) Need Help??


in reply to Strange code execution with 'AUTOLOAD'

DESTROY is the destructor for the class. If you use AUTOLOAD but not DESTROY, you will get the above error message, because AUTOLOAD is called for the DESTROY method (because AUTOLOAD catches all undefined method calls on the object), and you do not have a DESTROY method to call.

Since you have Object Oriented Perl, I suggest you look at page 112, at the section "Destructors and autoloading". It explains the situation far better than I can, and offers a solution (actually, two).

For those who don't have the book :), the best solution is to define an empty DESTROY method in your class:

sub DESTROY { }
The existence of this method will prevent AUTOLOAD from being called on object destruction.


Comment on Re: Strange code execution with 'AUTOLOAD'
Download Code
Re: Re: Strange code execution with 'AUTOLOAD'
by DrZaius (Monk) on Jul 01, 2001 at 23:40 UTC
    Another option is to set your autoload like this:
    sub AUTOLOAD { my ($self) = @_; # don't do any work if we are being called for DESTROY next if(substr($AUTOLOAD, -7) eq 'DESTROY'); $AUTOLOAD =~ /.*::get(_\w+)/ or die "No such method: $AUTOLOAD"; exists $self->{$1} or die "No such attribute: $1"; return $self->{$1} }
    Notice how it returns if this is a call to destroy? AUTOLOAD will never be called if there is a DESTROY method. I imagine sub DESTROY {} is faster, but the logic seems easier to maintain and less people will be asking "Why does my autoload work in this class and not that one?"
      Yes, this is the second option presented in OOP that I mentioned. :)

      However, as Damian Conway writes (and as you note), calling AUTOLOAD when you mean DESTROY, and when you *know* what you want to do with DESTROY, is less efficient than just defining an empty DESTROY method with

      sub DESTROY { }
      As for ease of maintenance, I would make the case that it is just as easy to maintain an empty method stub as a special case in AUTOLOAD, if not easier. And it is certainly clearer when looking at the code: rather than destruction behavior being buried in the definition of an AUTOLOAD, you have a defined DESTROY method to show that there is, in effect, no special destruction code.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://93045]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2014-12-21 03:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (102 votes), past polls