Reputation: 63892
Scenario:
My::Module
and Path::Class
and like...specific method
HashRef
where the values
are strings,so something like (very shortened):
package Some;
sub filename { file('/tmp/xxx') } #Path::Class the filename->stringify' returns the string value
sub myobj { My::Module->new(....) } #the myobj->stringvalue returns the string value
sub text { 'some text' }
sub data {
my $strhr;
$strhr->{$_} = $self->make_string $self->$_ for(qw(filename myobj text));
return $strhr;
}
sub make_string {
my($self, $val) = @_;
return $val->stringify if( VAL_IS_PATH::CLASS_OBJ ); #need help here
return $val->stringvalue if( VAL_IS_My::Obj_OBJ ); #and here
return $val if( VAL_IS_SIMPLE_STRING ); #and here
croak "unknown value";
}
In the real code the filename
and myobj
are defined with Moose, like:
has 'myobj' => (isa => 'My::Module', builder => ... ...);
But IMHO doing some Moose-ish deep-coercion
is in this case much more complicated than make a simple make_string
filter sub. But, i'm opened to any recommented solution...
So, the question is - how discover what object is the $val
, or if it is an simple Str
.
EDIT:
Based on @David W.'s comment i got the next:
sub make_string {
my($self, $val) = @_;
my $vref = ref $val; #for the "text" returns the string itself
return $val->stringify if( $vref =~ /^Path::Class/ ); #works
return $val->stringvalue if( $vref =~ /^My::Module/ ); #works
return $val if( VAL_IS_SIMPLE_STRING ); #returns the string itself, so how to check this???
croak "unknown value";
}
Upvotes: 2
Views: 338
Reputation: 13664
Use the isa
method. It's defined in the UNIVERSAL package (see perldoc UNIVERSAL
). All Perl classes implicitly inherit from UNIVERSAL.
use Scalar::Util qw( blessed );
if (blessed($val) and $val->isa('Path::Class')) {
print "It's a Path::Class object!\n";
}
Upvotes: 6