KSURi has asked for the wisdom of the Perl Monks concerning the following question:

Hello, monks!

I have 2 Moose-based classes:
Foo.pm:
package Foo; use Moose; coerce 'ArrayRef' => from 'Int' => via { [$_] }; has attr => ( is => 'rw', isa => 'ArrayRef[Int]', coerce => 1, ); # ... 1

and Bar.pm:
package Bar; use Moose; coerce 'ArrayRef' => from 'Int' => via { [$_] }; has another_attr => ( is => 'rw', isa => 'ArrayRef[Int]', coerce => 1, + ); # ... 1
When I try to use both classes in one script I get this:
A coercion action already exists for 'Int' at /usr/lib/perl5/site_perl +/5.8.8/Moose/Meta/TypeCoercion.pm line 87
The problem is that I have scripts which uses both Foo and Bar, and scripts which uses only one of them. So I have to define coercion in both classes.
How can I lexically scope coercion action for each class?

Replies are listed 'Best First'.
Re: Can't use two Moose classes with the same coercion action
by j1n3l0 (Friar) on Apr 24, 2009 at 15:22 UTC
    Hi,

    You should have a look at the updated best practices, specifically this part, which I think directly covers the issue you are having =)

    Hope that helps


    Smoothie, smoothie, hundre prosent naturlig!
      Thanks a lot! That's what I need.
      SOLVED
Re: Can't use two Moose classes with the same coercion action
by ww (Archbishop) on Apr 24, 2009 at 14:47 UTC

    Is this an XY Problem problem?

    At the cost of some editing of your scripts, does the unshown portion ( # ...) of either foo.pm or bar.pm restrict your ability to combine them in a single (say, foobar.pm) package, and thus step around the coercion issue?

      Maybe I missed some implication since I don't know Moose, but how can you combine two classes into one package?

      Incidentally, the OP's code doesn't compile for me.

      $ perl -e'use Foo; use Bar;' String found where operator expected at Foo.pm line 3, near "coerce 'A +rrayRef'" (Do you need to predeclare coerce?) String found where operator expected at Foo.pm line 3, near "from 'Int +'" (Do you need to predeclare from?) syntax error at Foo.pm line 3, near "coerce 'ArrayRef'" Compilation failed in require at -e line 1. BEGIN failed--compilation aborted at -e line 1.
        1. Open package
        2. put the classes in the package
        3. shake the package
        :D
Re: Can't use two Moose classes with the same coercion action
by castaway (Parson) on Apr 25, 2009 at 21:07 UTC

    You can also put your coercion in a separate types class, and include that in both Foo and Bar, then you only get them loaded once.

    C.
      I've done this right after I was advised to read documentation carefully :) But thanks