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

New function suggestion: eval-or-die

Thread Next
From:
Paul "LeoNerd" Evans
Date:
September 13, 2021 09:03
Subject:
New function suggestion: eval-or-die
Message ID:
20210913100302.53021763@shy.leonerd.org.uk
I have a few bits of code in unit tests of some new syntax that might
not even be valid perl, depending on the build). Therefore it -has- to
be a string eval.

  SKIP: {
     skip "No PL_infix_plugin", 1 unless XS::Parse::Infix::HAVE_PL_INFIX_PLUGIN;

     # Need to string-eval because this won't even compile on older perls
     my $result = eval '10 add 20';
     is( $result, 30, 'add infix operator' );
  }

Annoyingly, this eval() silently accepts syntax errors or runtime
exceptions, turning them into a simple undef; that unless I remember to
look in $@, gets lost.

To solve this I wrote a little(!) helper function:

  sub evalordie
  {
     my ( $code ) = @_;
     my @result = ("notset");

     my $ok = defined eval (
        wantarray         ? "do { \@result = $code }; 1" :
        defined wantarray ? "do { \$result[0] = $code }; 1 " :
                            "do { $code }; 1" );
     $ok or die $@;

     return @result if wantarray;
     return $result[0];
  }

The implementation of that is somewhat annoying as it tries to remain
context-transparent.

I feel it would be nice to provide a function of this behaviour in the
new "builtins" space at some point. Needs a better name though -
suggestions welcome.

-- 
Paul "LeoNerd" Evans

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

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