Ovid has asked for the wisdom of the Perl Monks concerning the following question:

If you have an anonymous function die, you can still "name" the function to make for better error messages:

use Carp 'croak'; sub { local *__ANON__ = 'my_anonymous_sub'; croak("Whee!"); }->(); __END__ Whee! at anon.pl line 9 main::my_anonymous_sub() called at anon.pl line 10

Unfortunately, if the error is in an eval, you get messsages like:

Some annoying error at (eval 7) line 17281

Can anyone think of a method of naming evals to make debugging easier?

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re: Named evals? (#line)
by tye (Sage) on Jan 29, 2008 at 15:31 UTC

    You mean besides starting the eval'd string with "\n#line 1 foobar.pl\n" ?

    - tye        

      Ah, I had forgotten about line directives. Thanks.

      Cheers,
      Ovid

      New address of my CGI Course.

Re: Named evals? (Sub::Name)
by lodin (Hermit) on Feb 01, 2008 at 12:08 UTC

    You can also name the subroutine by using Sub::Name:

    use Carp; use Sub::Name; subname( my_anonymous_sub => sub { croak("Whee!"); } )->(); __END__ Whee! at - line 6 main::my_anonymous_sub() called at - line 8
    The benefit of this is that you don't name all anonymous subroutines that are called inside this anonymous subroutine.
    use Carp; use Sub::Name; subname( my_anonymous_sub => sub { sub { carp("subname"); }->() } )->(); sub { local *__ANON__ = 'my_anonymous_sub'; sub { carp("*__ANON__"); }->() }->(); __END__ subname at - line 7 main::__ANON__() called at - line 8 main::my_anonymous_sub() called at - line 10 *__ANON__ at - line 15 main::my_anonymous_sub() called at - line 16 main::my_anonymous_sub() called at - line 17

    lodin