1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
package Catmandu::Fix::Bind::maybe;
use Catmandu::Sane;
our $VERSION = '1.2024';
use Moo;
use Scalar::Util qw(reftype);
use namespace::clean;
with 'Catmandu::Fix::Bind';
# Copied from hiratara's Data::Monad::Maybe
sub just {
my ($self, @values) = @_;
bless [@values], __PACKAGE__;
}
sub nothing {
my ($self) = @_;
bless \(my $d = undef), __PACKAGE__;
}
sub is_nothing {
my ($self, $mvar) = @_;
reftype $mvar ne 'ARRAY';
}
sub value {
my ($self, $mvar) = @_;
if ($self->is_nothing($mvar)) {
{};
}
else {
$mvar->[0];
}
}
sub unit {
my ($self, $data) = @_;
$self->just($data);
}
sub bind {
my ($self, $mvar, $func) = @_;
if ($self->is_nothing($mvar)) {
return $self->nothing;
}
my $res;
eval {$res = $func->($self->value($mvar));};
if ($@) {
return $self->nothing;
}
if (defined $res) {
return $self->just($res);
}
else {
return $self->nothing;
}
}
sub result {
my ($self, $mvar) = @_;
$self->value($mvar);
}
1;
__END__
=pod
=head1 NAME
Catmandu::Fix::Bind::maybe - a binder that skips fixes if one returns undef or dies
=head1 SYNOPSIS
do maybe()
foo()
return_undef() # rest will be ignored
bar()
end
=head1 DESCRIPTION
The maybe binder computes all the Fix function and ignores fixes that throw exceptions.
=head1 SEE ALSO
L<Catmandu::Fix::Bind>
=cut
|