in reply to Re: When to use eval
in thread When to use eval

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

Replies are listed 'Best First'.
Re^3: When to use eval
by hippo (Archbishop) on Feb 01, 2024 at 19:08 UTC
    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.

    🦛

Re^3: When to use eval
by stevieb (Canon) on Feb 01, 2024 at 18:43 UTC

    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

        I should have provided a better example. What autodie outputs is near identical to the diagnostic info I do manually. Nonetheless, it does do it automatically :)