I would love to write: list-returning try{} catch{}

((A followup to my message
  Subject: Metathread - Programs I would love to write
))

I would love to write

  use Syntax::Keyword::Try qw( try try_value );

  sub get_users { ... } # this may throw an exception

  say "$_ is a user" for try do { get_users() }
                         catch { @DEFAULT_USERS };

(see also [1])

This would be nice, as it

  * Uses the exception-handling syntax provided by
    `Syntax::Keyword::Try` to provide neater handling of exceptions

  * Reads in a neat list-yielding expression rather than needing to
    write it as purely control-flow and putting an assignment to a
    temporary array inside each of the blocks

However, currently this does not work, as list-returning `try do`
blocks do not work [2]:

  $ perl -Mstrict -Mwarnings -M5.024
  use Syntax::Keyword::Try qw( try try_value );
  say "NUMBER $_" for try do { 1, 2, 3 } catch {};
  __END__

  'try do' syntax is experimental and may be changed or removed without
  notice at - line 2.
  Useless use of a constant (2) in void context at - line 2.
  NUMBER 3

This is due to the way the context within the `try do` block is
compiled by perl, but before I get into that I want first to establish
the overall theme for this thread; namely that:

  We believe the ability to use try/catch syntax as a list-returning
  expression is a useful ability to try to achieve.

If we generally agree it'd be nice to be able to write this sort of
thing, then I'll expand more on why it currently doesn't work, why I
believe p5p are the place to begin solving it, and then we can work on
how to fix it.

-----

[1]: The exact spelling of `try do` is still under consideration; I may
     rename it to `checked` as per
     https://rt.cpan.org/Ticket/Display.html?id=121267

[2]: This is even asserted in unit tests:
     https://metacpan.org/source/PEVANS/Syntax-Keyword-Try-0.10/t/20try-do.t#L37

-- 
Paul "LeoNerd" Evans

leonerd@leonerd.org.uk      |  https://metacpan.org/author/PEVANS
http://www.leonerd.org.uk/  |  https://www.tindie.com/stores/leonerd/
0
leonerd
7/3/2019 11:33:53 AM
perl.perl5.porters 47809 articles. 1 followers. Follow

1 Replies
50 Views

Similar Articles

[PageSpeed] 19

"Paul \"LeoNerd\" Evans" <leonerd@leonerd.org.uk> wrote:
[...]
:This is due to the way the context within the `try do` block is
:compiled by perl, but before I get into that I want first to establish
:the overall theme for this thread; namely that:
:
:  We believe the ability to use try/catch syntax as a list-returning
:  expression is a useful ability to try to achieve.

I see no reason why perl _should_ be doing anything to stop that being
possible: in the absence of some compelling reason why it should, I
think it should not.

Hugo
0
hv
7/5/2019 1:04:56 PM
Reply: