http://www.perlmonks.org?node_id=11130030


in reply to Coerce or transform with Types::Param

Something like this?

use Types::Standard qw( Str Maybe ); use Types::Common::String qw( StrLength ); my $Caption = StrLength[ 1, 2780 ]; my $EmptyStr = Str->where( q{ $_ eq '' } ); my $MaybeCaption = Maybe->of( $Caption )->plus_coercions( $EmptyStr => + q{ undef } ); use Test::More; ok( $MaybeCaption->check( 'My pic' ), 'Good caption passes type constr +aint' ); ok( $MaybeCaption->check( undef ), 'Undef passes type constraint' ); ok( ! $MaybeCaption->check( [] ), 'Arrayref fails type constraint' ); is( $MaybeCaption->coerce( '' ), undef, 'Empty string coerced to undef +' );

Basically, add the coercion to the Maybe[Caption], not to Caption.

But the important thing is to make sure that the empty string isn't considered a valid Caption. Because if a value is valid, it is never coerced.