use strict; use warnings; use Test::More; use Scalar::Util qw(weaken isweak); use Devel::Refcount qw(refcount); my $A = bless {}, 'Monkey'; is(refcount($A), 1, 'an object has a refcount'); my $B = $A; is(refcount($A), 2, 'additional ref to the object increases the refcount'); $B = undef; is(refcount($A), 1, 'removing a ref to the object decreases the refcount'); do { my $C = $A; is(refcount($A), 2, 'reference in a scope increases refcount'); }; is(refcount($A), 1, '$C fell out of scope, so decreased ref count'); my $D = $A; is(refcount($A), 2, 'another ref which will increase ref count'); weaken $D; is(refcount($A), 1, 'weakening the ref means it is not included in the ref count'); ok($A == $D, 'yet $A and $D are still the same object'); my $destroyed = 0; sub Monkey::DESTROY { $destroyed++ }; $A = undef; is($destroyed, 1, 'undefining $A destroyed the object; $D was a weak ref so did not prevent destruction'); ok(!defined $D, '$D is now undefined'); done_testing;