Exception-Delayed

 view release on metacpan or  search on metacpan

lib/Exception/Delayed.pm  view on Meta::CPAN

package Exception::Delayed;

# ABSTRACT: Execute code and throw exceptions later

use strict;
use warnings;

our $VERSION = '0.002';    # VERSION

sub wantscalar {
    my ( $class, $code, @args ) = @_;
    my $RV;
    eval { $RV = scalar $code->(@args); };
    if ($@) {
        return bless { error => $@ } => $class;
    }
    else {
        return bless { result => \$RV } => $class;
    }
}

sub wantlist {
    my ( $class, $code, @args ) = @_;
    my @RV;
    eval { @RV = $code->(@args); };
    if ($@) {
        return bless { error => $@ } => $class;
    }
    else {
        return bless { result => \@RV } => $class;
    }
}

sub wantany {
    my ( $class, $wantarray, $code, @args ) = @_;
    if ($wantarray) {
        return $class->wantlist( $code, @args );
    }
    else {
        return $class->wantscalar( $code, @args );
    }
}

sub result {
    my ($self) = @_;
    if ( exists $self->{error} ) {
        die $self->{error};
    }
    else {
        my $result = delete $self->{result};
        if ( ref $result eq 'ARRAY' ) {
            return @$result;
        }
        elsif ( ref $result eq 'SCALAR' ) {
            return $$result;
        }
        else {
            return;
        }
    }
}

1;

__END__

=pod

=head1 NAME

Exception::Delayed - Execute code and throw exceptions later

=head1 VERSION

version 0.002

=head1 SYNOPSIS

    my $x = Exception::Delayed->wantscalar(sub {
        ...
        die "meh";
        ...
    }); # code is immediately executed

    my $y = $x->result; # dies with "meh"

=head1 DESCRIPTION

This module is useful whenever an exception should be thrown at a later moment, without using L<Try::Tiny> or similiar.



( run in 0.716 second using v1.01-cache-2.11-cpan-99c4e6809bf )