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

New function suggestion: eval-or-die

Thread Next
Paul "LeoNerd" Evans
September 13, 2021 09:03
New function suggestion: eval-or-die
Message ID:
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

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

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