in reply to When to use eval

What does eval catch? A function that issues a die?

It allows the execution of code which may error (ie. die) without terminating the enclosing running instance.

$ perl -E 'eval { die "Ay, caramba!"; }; say "foo"' foo
For instance ,open , returns undef when failing but it doesn't kill the rest of the program due to the 'exception'.

It does if you use autodie; so you might use a block eval in that situation.

Note that there are cleaner ways to trap and check for exceptions. In a recent enough perl you can use try. For older perls there are modules such as TryCatch, Try::Tiny, etc.


🦛

Replies are listed 'Best First'.
Re^2: When to use eval
by Anonymous Monk on Feb 01, 2024 at 18:03 UTC
    >which may error (ie. die)
    what other conditions except of 'die' can eval trap?
    And autodie does consider 'undef' as an exception?
    There's also a Fatal module I think.What is it's difference with 'autodie'?
      what other conditions except of 'die' can eval trap?

      Depends what you count as "except of 'die'". It will trap other run-time errors which would be fatal such as de-referencing non-references or failures of require, etc.

      The documentation for eval is pretty extensive. All the answers you seek should be there.

      And autodie does consider 'undef' as an exception?

      Not explicitly. See autodie.

      here's also a Fatal module I think.What is it's difference with 'autodie'?

      You haven't read the docs for Fatal either then?

      Fatal has been obsoleted by the new autodie pragma. Please use autodie in preference to Fatal. autodie supports lexical scoping, throws real exception objects, and provides much nicer error messages.

      🦛

      I have never used autodie, but my understanding that it just makes functions that normally return false on failure die instead. So if you have this code:

      open my $fh, '<', 'filename.txt';

      ...and you have autodie in use, the code will behave as if it were written like this:

      open my $fh, '<', 'filename.txt' or die $!;

      Myself, I prefer to be able to see within the code if something is designed to die explicitly or not so I would never use such a contraption as autodie.

        Actually, autodie is way better than or die $!. It would rather be like this:

        open my $fh, '<', $filename or die qq(Can't open $filename for $mode: '$!')

        It takes care to inform about the filename (in quotes, so that it stands out against the constant text), the open mode, and also wraps $! in quotes. That is exactly why I often use autodie, especially in short and quick programs when I don't want to spend time on crafting error messages.

        Which error message would you prefer:

        Permission denied at demo1.pl line 2.
        Can't open 'filename.txt' for reading: 'Permission denied' at demo2.pl line 2