Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re^3: when is destroy function called

by Athanasius (Chancellor)
on Mar 02, 2013 at 08:19 UTC ( #1021398=note: print w/replies, xml ) Need Help??

in reply to Re^2: when is destroy function called
in thread when is destroy function called

Sorry, my bad. I added use warnings to my copy of ggoebel’s script; forgot that it wasn’t in the original; and then compounded the confusion by referring to the warning which results as an “error’. The warning in question is:

Use of uninitialized value in print at...

which comes from the inclusion of undef($obj) in the arguments to the print statement.

The evals are there to allow the print statement to complete in spite of the error (exception) which results from the attempt to call a method on an undefined object. That error is:

Can't call method "exterminate" on an undefined value at (eval 2) line + 1.

which in the original example was captured by the eval and printed by the statement print $@ if $@;.

I agree that your example “seems to prove” my conclusion; but I wanted to be sure. Hence my provision of an additional resource which is altered within the DESTROY method. Adapting your example:

#! perl use strict; use warnings; use 5.010; $| = 1; my $num = 42; { package Dog; sub new { return bless {}; } sub bark { say 'Bow wow!'; } sub DESTROY { print "destroy\n"; ++$num; } } my $dog = Dog->new(); print 'hello ', $dog->bark(), undef $dog, eval('$dog->bark()'), "|$num|", "world\n"; print $num;


18:02 >perl Bow wow! Use of uninitialized value in print at line 31. hello 1|42|world destroy 43 18:02 >

which shows that $num is incremented only after the print statement completes, and not at the point where the reference count of $dog falls to zero. (Note that the “1” in the output comes from the say statement in Dog::bark, which returns true on success.)

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1021398]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2018-06-25 01:32 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.