package Try::Chain; ## no critic (TidyCode)

use strict;
use warnings;
use parent qw(Exporter);
use Try::Tiny qw(try catch finally);

our $VERSION = '0.001';

our @EXPORT_OK = qw( try catch finally try_chain $call_m );

sub try_chain (&;@) { ## no critic (SubroutinePrototypes)
    my ( $chain_code, @more ) = @_;

    my $check_code = sub {
        ## no critic (ComplexRegexes)
        m{
            \A \QCan't call method "\E .*? \Q" on an undefined value\E \b
            | \A \QCan't locate object method "\E .*? \Q" via package\E \b
            | \A \QCan't use an undefined value as a HASH reference\E \b
            | \A \QCan't use an undefined value as an ARRAY reference\E \b
        }xms
            or die $_; ## no critic (RequireCarping)
        ## use critic (ComplexRegexes)

        return ();
    };

    return @more
        ? try {
            try { $chain_code->() } catch { $check_code->() };
        } @more
        : try { $chain_code->() } catch { $check_code->() };
}

# call method
our $call_m = sub { ## no critic (PackageVars)
    my ( $self, $method, @more ) = @_;

    return $self ? $self->$method(@more) : ();
};
# $any->$call_m('foo')->$call_m('bar' => @params)->$call_m('baz')

# $Id$

1;

__END__

=head1 NAME

Try::Chain - Call method, hash and/or array chains with break on undef

=head1 VERSION

0.001

=head1 SYNOPSIS

The module exports:

    try       - imported from Try::Tiny
    catch     - imported from Try::Tiny
    finally   - imported from Try::Tiny
    try_chain - implemented in this module
    $call_m   - implemented in this module

Import what needed. The following code describes the full import:

    use Try::Chain qw( try_chain finally try_chain $call_m );

=head1 EXAMPLE

Inside of this Distribution is a directory named example.
Run this *.pl files.

=head1 DESCRIPTION

Call method, hash and/or array chains with break on undef means,
that in some cases it is ok to get back nothing late or early.

=head2 Problem

In case of method chain like

    my $scalar = $obj->foo(1)->bar(2)->baz(3);

    my %hash = (
        any => 'any',
        baz => scalar $obj->foo(1)->bar(2)->baz(3),
    );

and foo or bar can can return nothing or undef, you get an error:
Can't call method ... on an undefined value.

A quick solution is:

    my $scalar
        = $obj->foo(1)
        && $obj->foo(1)->bar(2)
        && $obj->foo(1)->bar(2)->baz(3);

    my %hash = (
        any => 'any',
        baz => scalar $obj->foo(1)
               && $obj->foo(1)->bar(2)
               && $obj->foo(1)->bar(2)->baz(3),
    );

In case of method foo and/or bar is performance critical code
it is a bad idea to call the method code more then one time.
The the solution looks like this:

    my $foo    = $obj->foo(1);
    my $bar    = $foo && $foo->bar(2);
    my $scalar = $bar && $bar->baz(3);

    my %hash = (
        any => 'any',
        baz => do {
            my $foo = $obj->foo(1);
            my $bar = $foo && $foo->bar(2);
            $bar && scalar $bar->baz(3);
        },
    );

=head2 Solution

This module allows to call the chain by ignoring all undef errors in block:

    my $scalar = try_chain { $obj->foo(1)->bar(2)->baz(3) };

    my %hash = (
        any => 'any',
        baz => scalar try_chain { $obj->foo(1)->bar(2)->baz(3) },
    );

Or better step by step?

    my $scalar = $obj->$call_m('foo', 1)->$call_m('bar', 2)->$call_m('baz', 3);

    my %hash = (
        any => 'any',
        baz => scalar $obj
            ->$call_m('foo', 1)
            ->$call_m('bar', 2)
            ->$call_m('baz', 3),
    );

Also possible with maybe not existing hash or array references:

    ... = try_chain {
        no autovivication; # optional
        $any->foo->{key}->bar(@params)->[0]->baz
    };

Full Try::Tiny support:

    ... = try_chain { ... } catch { ... } finally { ... };

=head2 Solution for the autovivification Problem

Switch off possible autovivication:

    $result = try_chain {
        no autovivification;
        $any->foo->{key}->bar(@params)->[0]->baz;
    };

    @result = try_chain {
        no autovivification;
        $any->foo->{key}->bar(@params)->[0]->baz;
    };

=head1 SUBROUTINES/METHODS

=head2 sub try_chain

Calls the whole try block breaks and ignores in undef.

=head2 sub $call_m

Calls the next method. For methods only.

=head1 DIAGNOSTICS

none

=head1 CONFIGURATION AND ENVIRONMENT

nothing

=head1 DEPENDENCIES

L<parent|parent>

L<Exporter|Exporter>

L<Try::Tiny|Try::Tiny>

=head1 INCOMPATIBILITIES

not known

=head1 BUGS AND LIMITATIONS

none

=head1 SEE ALSO

L<Try::Tiny|Try::Tiny>

L<autovivification|autovivification>

=head1 AUTHOR

Steffen Winkler

=head1 LICENSE AND COPYRIGHT

Copyright (c) 2017,
Steffen Winkler
C<< <steffenw at cpan.org> >>.
All rights reserved.

This module is free software;
you can redistribute it and/or modify it
under the same terms as Perl itself.