Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^3: when is destroy function called

by Athanasius (Monsignor)
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;

Output:

18:02 >perl 552_SoPW.pl Bow wow! Use of uninitialized value in print at 552_SoPW.pl 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,


Comment on Re^3: when is destroy function called
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2014-08-20 22:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (124 votes), past polls