存储所见对象 ID 的哈希值,以确保您只计算每个对象一次。您可以使用Hash::Util::FieldHash或Object::ID来做到这一点。
idhash 的优点是它不会人为地使对象保持活动状态。随着每个对象被销毁,它的条目将从 idhash 中删除。它还具有跨线程工作的好处。
package Foo;
use strict;
use warnings;
use v5.10;
use Hash::Util::FieldHash qw(idhash register id);
idhash my %objects;
sub new {
my $self = bless {}, shift;
register $self, \%objects;
$objects{$self} = 1;
say "Creating ".id $self;
my $num_objects = keys %objects;
say "There are now $num_objects alive.";
return $self;
}
sub DESTROY {
my $self = shift;
my $num_objects = keys(%objects) - 1;
say "Destroying ".id $self;
say "There are $num_objects left alive.";
}
{
my $obj1 = Foo->new; # 1 object
my $obj2 = Foo->new; # 2 objects
{
my $obj3 = Foo->new; # 3 objects
} # 2 objects
my $obj4 = Foo->new; # 3 objects
} # 0 objects
__END__
Creating 4303384168
There are now 1 alive.
Creating 4303542768
There are now 2 alive.
Creating 4303545192
There are now 3 alive.
Destroying 4303545192
There are 2 left alive.
Creating 4303638136
There are now 3 alive.
Destroying 4303542768
There are 2 left alive.
Destroying 4303384168
There are 1 left alive.
Destroying 4303638136
There are 0 left alive.
或者,由于创建的每个对象都将被销毁,因此仅在对象被销毁时才计数。