oyse has asked for the wisdom of the Perl Monks concerning the following question:
As part of implementing a module that need to find out at runtime what methods an object supports I tested the following:
package TestPackage; use Data::Dump qw( dump ); my $obj = bless {}, __PACKAGE__; print 'Can dump()' if $obj->can( 'dump' ); print 'Can not_a_sub()' if $obj->can( 'not_a_sub' );
This prints "Can dump()" while in reality $obj does not implement dump(). Is there any other way to find out which methods an object implements, i.e. it's interface?
Update:As usual I have given too little background to my question.
The reason I wanted to discover the interface of an object was that I was trying to implement yet another module for parameter validation for subroutines. Yes I know that there are more than enough of these already, but none of them works exactly I want them to and besides it was a challenge. Anyway, I wanted to be able to specify the type of a parameter, but instead of doing a isa() check on the supplied argument, it should check that it had the right functions. The check it self can be implemented via can(), but the module should be able to be given a package name and then determine what methods and object should be able to do. This is probably best illustrated with an example.
package A::Type; use Some::Module qw( a_func ); sub new { #standard constructor } sub a_method { } sub another_method { } package Another::Module; use Signature::Checker; sub func : Signature( A::Type parameter ) { }
The intention in this example is that the module Signature::Checker in some way adds parameter validation to subroutines that have the attribute Signature attached to them. When the Signature::Checker sees the type A::Type it should try to discover what methods A::Type implements. By using can() it will see the functions a_func(), new(), a_method() and another_method() which was not as intended.
As far as I understand Corion's answer this is not possible to implement in a general way. stvn's suggestion would work, but if I understand correctly, restrict the solutuion to only work with classes implemented with Moose. For me that would partly defeat the purpose of the module.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Finding the interface implemented by an object
by stvn (Monsignor) on Nov 28, 2007 at 01:35 UTC | |
by j1n3l0 (Friar) on Nov 28, 2007 at 14:01 UTC | |
by stvn (Monsignor) on Nov 28, 2007 at 15:19 UTC | |
|
Re: Finding the interface implemented by an object
by Corion (Patriarch) on Nov 27, 2007 at 21:09 UTC | |
|
Re: Finding the interface implemented by an object
by shmem (Chancellor) on Nov 27, 2007 at 23:14 UTC | |
|
Re: Finding the interface implemented by an object
by RaduH (Scribe) on Nov 27, 2007 at 21:13 UTC | |
|
Re: Finding the interface implemented by an object
by aquarium (Curate) on Nov 27, 2007 at 22:29 UTC |