Note that UNIVERSAL::isa does not work for me in this case.
I do not want to walk up the inheritance tree as __PACKAGE__->isa('UNIVERSAL') does.
Here is an example:
use 5.10.1;
use strict;
use warnings;
use utf8;
{
package Parent;
#How to do this more elegantly?
sub inherits_from_parent {
no strict 'refs';
return (__PACKAGE__ eq @{"$_[0]\::ISA"}[0]);
}
}
{
package Child;
use parent -norequire, qw(Parent);
}
package main;
say "Child directly inherits from Parent"
if Child->inherits_from_parent;
#not wat I want
say 'Child is universal:'.Child->isa('UNIVERSAL');
Is there a better way (without using no strict 'refs';) to detect the direct parent of a class?
Thanks.
I don’t think that there is anything wrong with looking at the
@ISAarray for the class, in fact, this is what Perl does and almost certainly what any diagnostic module would do. Remember that there is nothing evil about turning off parts ofstrictwhen you know why you are doing it, and this is one of those cases.To your actual question, a little Googling has yielded a few possibilities, of which Curtis Poe (Ovid)’s
Class::Sniffmay be the best example.I know that
Data::Printerprints out the class hierarchy when you dump an object. Its output is meant for human readers, but you might be able to look at its code to see what it does. Again, I’m almost certain it does exactly what you do in your example!