On 12/24/2009 05:34 PM, Chris Prather wrote:
On Thu, Dec 24, 2009 at 4:55 PM, Mike Friedman<fri...@friedo.com>  wrote:
You should be able to do this with triggers. For example:

has foo =>  ( isa =>  'Str', is =>  'rw', trigger =>  \&_munge_foo );

sub _munge_foo {
    my ( $self, $new_foo, $old_foo ) = @_;

    $new_foo =~ s/\W+/_/gs;
    $self->{foo} = $new_foo;
}

The trigger will be called every time foo is set, including in the constructor.


Mike
A Trigger really is the wrong way to go about this. While yes this
will work it's not considered "best practice".

What you *do* want is a TypeConstraint and a Coercion.

use Moose::Util::TypeConstraints;

subtype MyAppCleanStr =>  as Str =>  where { $_ !~ /\W+/gs }; # make a
TypeConstraint based on what you want
coerce MyAppCleanStr =>  from Str =>  via { $_ =~ s/\W+/_/gs }; # define
how to convert dirty Str to a Clean Str

has foo =>  ( isa =>  'MyAppCleanStr', is =>  'rw', coerce =>  1): # tell
Moose you want to coerce for this attribute.

-Chris
Great -- thanks, guys.  I'll read up on both of those.

-Sir

Reply via email to