A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Jump to

Quick reference

Coercions in Perl

Lately I've been using Moo instead of Moose, and I came across Type::Tiny Coercions, but I found the documentation difficult to follow.

My colleagues figured out a working example:

use v5.26.0;
use Test::Most;
use Types::Standard qw< Enum Bool Str >;
use Type::Utils qw< enum >;
my $YesNoString = enum( [qw/ yes no /] )->plus_coercions(
Bool, sub { $_ ? 'yes' : 'no' },
Str, sub { lc },
);
{
package Temp;
use Moose;
use Types::Standard qw( Bool Join Str );
has delete => ( coerce => 1, is => 'ro', isa => $YesNoString );
has tags => ( coerce => 1, is => 'ro', isa => Str->plus_coercions(Join[' ']) );
}
{
cmp_methods(
new_ok( Temp => [ delete => 1, tags => [qw(foo bar)] ] ),
[
delete => 'yes',
tags => 'foo bar',
],
'attributes are coerced as expected',
);
# # breakdown of cmp_methods() and new_ok()
# my @args = (
# delete => 1,
# tags => [qw(foo bar)],
# );
# my $obj = Temp->new(@args);
# isa_ok $obj, 'Temp', 'object isa okaya';
#
# is($obj->delete, 'yes', "delete() = yes");
# is($obj->tags, "foo bar", "tags() = foo bar");
}
done_testing;
view raw coercion.pl hosted with ❤ by GitHub
"You need an enum type that allows only 'yes' and 'no'.  It's also important that you order your coercions with the most specific first.  (Bool before Str)"

"The arguments inside the `plus_coersions( ... )` are basically `$FromType, $coercion_sub`"

Thanks Nelo and Mark S.