[Perl5-syntax] How to test for a role in a method signature

Piers Cawley pdcawley at bofh.org.uk
Fri Mar 4 06:32:59 GMT 2011


On Fri, Mar 4, 2011 at 1:32 AM, Buddy Burden <barefootcoder at gmail.com> wrote:
> Guys,
>
> Michael (Schwern) suggested I seek the collected wisdom of the group
> here on this question.  Basically, what makes sense to me is something
> like:
>
>    {
>        package Blargy;
>        use Role::Basic;
>    }
>
>    {
>        package Foo;
>        use Method::Signatures;
>
>        method new ($class:) { bless {}, $class }
>        method doit ($bl does Blargy)            # proposed syntax
>        {
>            # whatever
>        }
>    }
>
>    my $f = Foo->new;
>    $f->doit(42);                                            # should
> give run-time error because !(42 does Blargy)
>
> (I used Role::Basic here just to take Moose out of the equation).  So
> that's the syntax that makes sense to me, and I could've sworn it
> worked that way in Perl6 too.  But now I can't find it in any of the
> Synopses.
>
> (Note that MXMS allows a "does" in the signature, but it means
> something totally different (it's essentially a synonym for 'is' and
> applies a trait to the parameter).)
>
> So, the question is, does this syntax make sense to everyone?  It
> seems intuitive to me, but intuitiveness is often in the eye of the
> beholder, so it seems prudent to ask.  If this is _not_ a desired
> syntax, what _would_ be a good syntax for run-time verification of a
> method parameter (similar to how 'Blarg $bl' would verify that
> $bl-isa(Blarg))?  And, just as a point of reference, does anyone know
> how this will be achieved in P6?
>
> TIA for your time.

Personally, I prefer the flow of 'Typed $parameter does coerce', where
the constraint declaration is always to the left of the parameter name
and the right hand side is for declaring stuff about how the parameter
is initialized. I would encourage anyone wanting to constrain by type
to declare a type along the lines of "subtype DoesRole, as role_type
'Role'" and, where the constraint is a simple package name, I'd look
at writing something like:

$constraint->can('meta') ? $constraint->meta->has_instance( $param ) :
$param->isa( $constraint )

But I'm not sure that various Moose meta classes implement
'has_instance' or its equivalent. If not, they jolly well should do.



More information about the Perl5-syntax mailing list