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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Coerce or transform with Types::Param
by 1nickt (Canon) on Mar 21, 2021 at 12:41 UTC | |
by tomred (Acolyte) on Mar 21, 2021 at 15:23 UTC | |
|
Re^2: Coerce or transform with Types::Param
by tomred (Acolyte) on Mar 21, 2021 at 15:25 UTC | |
by tobyink (Canon) on Mar 21, 2021 at 20:33 UTC |