develooper Front page | perl.perl5.porters | Postings from January 2021

Re: Adding a try/catch syntax to Perl

Thread Previous | Thread Next
From:
Paul "LeoNerd" Evans
Date:
January 22, 2021 21:16
Subject:
Re: Adding a try/catch syntax to Perl
Message ID:
20210122211656.7b85ce84@shy.leonerd.org.uk
On Fri, 22 Jan 2021 20:42:11 +0000
Philip R Brenan <philiprbrenan@gmail.com> wrote:

> Might it be better to have the exception in *$@* as "in the best it
> is"? This would save updates to documentation, reduce user confusion
> and allow the *($e)* to be dispensed with entirely in the most common
> use cases. 

$@ is well-known to be extremely fragile, a variable whose value is
prone to being changed underneath you without provocation. It is best
avoided. In fact it can be considered similar to the original form of
`foreach` without a lexical var, simply aliasing the `$_` variable. Too
often you end up accidentally mutating that variable and hence the
original value in the array. The use of lexicals `foreach my $VAR` was
added to make that much safer.


It is the avoidance of this which lead to the design of `catch (VAR)`
in the first place. Originally SKT just did try/catch with no var,
expecting the user to read from $@ as you described. Quickly in use it
turned out everyone just did

  catch {
    my $e = $@;
    ... # use $e and ignore $@

all the time, to avoid the volatility of $@.

Around SKT version 0.12 I added `catch my $VAR` syntax to simplify
this.

It was later found that that doesn't play well with the typed dispatch
idea, whereas `catch ($VAR)` does; which was then added in 0.14, and
the previous form marked deprecated.

Version 0.18 de-experimentalises the `catch (VAR)` form. I notice that
`catch my $VAR` has been totally removed from the code, though it seems
I did not record in the Changes file when that occurred.

You can read for yourself at

  https://metacpan.org/source/PEVANS/Syntax-Keyword-Try-0.21/Changes

Please acquaint yourself with the mistakes of history, so that you are
not doomed to repeat them.

-- 
Paul "LeoNerd" Evans

leonerd@leonerd.org.uk      |  https://metacpan.org/author/PEVANS
http://www.leonerd.org.uk/  |  https://www.tindie.com/stores/leonerd/

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