I've got a polymorphic array of objects which implement two (informal) interfaces. I want to be able to differentiate them with reflection along the lines of:
if (hasattr(obj, 'some_method')) {
# `some_method` is only implemented by one interface.
# Now I can use the appropriate dispatch semantics.
} else {
# This must be the other interface.
# Use the alternative dispatch semantics.
}
Maybe something like this works?:
if (*ref(obj)::'some_method') {
# ...
I have difficulty telling when the syntax will try to invoke a subroutine and when it will return a subroutine reference. I'm not too familiar with package symbol tables ATM and I'm just trying to hack something out. :-)
Thanks in advance!
use Scalar::Util qw(blessed);
if( blessed($obj) and $obj->can('some_method') ){
}
"can" here is a method inherited by all classes from UNIVERSAL . Classes can override this method, but its not a good idea to.
Also, "can" returns a reference to the function, so you can do:
$foo->can('some_method')->( $foo , @args );
or
my $sub = $foo->can('some_method');
$foo->$sub( @args );
Edit Updated Chain Syntax, thanks to Brian Phillips
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