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,
|