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

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

Thread Next
Paul "LeoNerd" Evans
July 3, 2019 11:34
I would love to write: list-returning try{} catch{}
Message ID:
((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 {};

  '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.

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

[2]: This is even asserted in unit tests:

Paul "LeoNerd" Evans      |  |

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About