Is there a straightforward way to check if an instance inherits from a particular class?
I've put together something that works, but it uses eval to climb back through packages' @ISA variables. Can I get more elegant?
Here's the need. I'm modeling sentence structure. I have a base class, ucf::Constit::ScopeConstit; with other classes inheriting as below:
ucf::Constit::ScopeConstit;
ucf::Constit::NounCn;
ucf::Constit::PrepCn;
several other kinds of Prep
ucf::Constit::VerbCn;
ucf::Constit::ModifierCn;
I have
$sentence, which an array of constit-instances, all drawn from these classes. I want derive a shorter array, $NPs, consisting of only those constits which inherit from ucf::Constit::NounCn. So, I need a function
InheritsFrom($ObjRef, $className) which returns TRUE iff $ObjRef inherits from $className. I coded up this, which works:
package base::ObjInheritance;
use strict;
use Carp;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(InheritsFrom);
use List::Util qw(first);
sub InheritsFrom{
my($ObjRef, $className) = @_; # I"ve scrubbed the error checking
+ code for clarity
my $oref = ref $ObjRef;
&IF1($oref, $className)}
sub IF1{
# $ref and $className will bo
+th be strings, which name classes.
my($ref, $className) = @_;
return 1 if $ref eq $className; # We've found an inheritance!
my $isa = '@' . $ref . '::ISA'; # Rely on the ref being the p
+ackage
my @parents = eval $isa; # Find the @ISA for the packa
+ge and eval it
foreach my $heather (@parents){ # Recurse on the parents
next if $heather eq 'Exporter';
if(&IF1($heather, $className)){
return 1}};
0} # Found no inheritance in this branch.
So now, I can find my $NPs
my $NPs = [grep &InheritsFrom($_, 'ucf::Constit::NounCn'), @$sentenc
+e]
Was there a cleaner way to have done this, without using eval?
Thanks
throop