I have a Perl library that uses many objects of some (about 3 or 4) classes during its operation.
In testing code, I'd like to ensure it isn't too many (I'm not talking about memory leaks, I know how to check that). To this end, I thought I could count every object used and check the maximum used during the run on the test data. Then, I would compare the obtained number to some guess about how many objects the library should use.
However, I've got problems implementing this. I thought about two possible ways:
intercept Package::new and Package::DESTROY. However, this has a little catch that in that package, new doesn't always return a new object. Sometimes, it uses a preexisting one (the objects are used as immutables, so it shouldn't matter much). So I'd have to track each individual object to see if it existed before.
intercept Package::bless and Package::DESTROY. This should work, but seems a little unorthodox.
The question is, which of those ways is more likely to succeed (maybe what is commonly used in similar situations), and secondly, how would I even implement the second way (would I have to override Package::bless for all packages in question or only base classes etc.).
Try something like this (not tested):
my $Package_objects = {};
my $override_new = *Package::new{CODE};
*Package::new = sub {
my $self = $override_new->(@_);
# Interpolate $self as string to get "HASH(0x12345)"; save package name
$Package_objects->{ "$self" } = 'Package';
return $self;
};
my $override_dest = *Package::DESTROY{CODE};
*Package::DESTROY = sub {
delete $Package_objects->{ "$_[0]" };
$override_dest->(@_);
};
Probably this is most barbaric method, but must work without 3rd party modules ;)
With regard to how to intercept bless (not Package::bless, bless is a builtin, not some kind of method), most builtins are overridable (see http://perldoc.perl.org/perlsub.html#Overriding-Built-in-Functions). The replacement bless function would perform your tracking (if blessing an object into your target class) and then call CORE::bless to actually perform the bless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With