develooper Front page | perl.perl5.porters | Postings from July 2020

Re: try/catch and CLEANUP/FINALLY/&c.

Thread Previous | Thread Next
From:
Felipe Gasper
Date:
July 20, 2020 13:33
Subject:
Re: try/catch and CLEANUP/FINALLY/&c.
Message ID:
16A9E422-D432-48E1-8B55-9D839662FD3B@felipegasper.com

> On Jul 20, 2020, at 9:08 AM, Paul LeoNerd Evans <leonerd@leonerd.org.uk> wrote:
> 
> On Sat, 18 Jul 2020 22:06:58 -0400
> Felipe Gasper <felipe@felipegasper.com> wrote:
> 
>> This aspect seems common to both finally and CLEANUP blocks.
> 
> No, they are exactly opposite here. This is the point I was trying to
> make.
> 
>  {
>    my $new_var = ...
>    CLEANUP { $new_var->dispose }  # works just fine
>  }
> 
> If you wanted to write this in try/finally notation you end up with
> another wrapping block around it, and a hoisted variable:
> 
>  {
>    my $new_var;
>    try {
>      $new_var = ...
>    }
>    finally {
>      $new_var->dispose;
>    }
>  }
> 
> I much prefer the conciseness of the CLEANUP block.

As a replacement for Scope::Guard, FINALLY{} makes a lot of sense, and your point about how widely implemented the FINALLY pattern is on CPAN is well-taken. It does seem a bit redundant with DESTROY blocks, at least in the case of bless()ed references, so assuming this lands it might be nice to compare those two forms of tail logic in the docs.

As to obviating stuff like Try::Catch, though … is the idea, then, that we’d do something the likes of this?

=====
    my $thing = My::Thing->new();

    FINALLY { $thing->clean_up() }

    eval { $thing->frobnicate(); 1 } or do {
        if ($@ isa 'X::Error1') { .. }
        elsif ($@ isa 'X::Error2') { .. }
        else { die }
    };
=====

Thank you!

-F

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About