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

I use quite a bit of generated code in my program (meaning Perl code that is assembled in a string then eval-ed), for example, when generating argument validator code using Data::Sah.

This turns out to be rather annoying when debugging warning/error messages. Perl only shows the filename as "(eval NUMBER)", for example:

perl -wE'eval "1+1; 1"; eval "\n; 1+1; 2"' Useless use of a constant (2) in void context at (eval 1) line 1. Useless use of a constant (2) in void context at (eval 2) line 2.

It would be slightly more helpful if there were a way to change the filename into something more descriptive, so the warn/error message can be something like:

Useless use of a constant (2) in void context at (validator code for X + generated by Foo/Bar.pm line 234) line 1. Useless use of a constant (2) in void context at (validator code for Y + generated by Foo/Baz.pm line 99) line 2.

Replies are listed 'Best First'.
Re: Changing "filename" of eval-ed code
by Discipulus (Canon) on May 20, 2016 at 08:28 UTC
    If i understand what you mean, you may profit of $^P as described in perlvar
    $^P= 0x100; # x100 # Provide informative "file" names for evals based on the place th +ey were compiled. perl -wlE "BEGIN{$^P= 0x100}eval '1+1; 1'; eval qq(\n;1+1;2)" Useless use of a constant (2) in void context at (eval 1)[-e:1] line 1 +. Useless use of a constant (2) in void context at (eval 2)[-e:1] line 2 +.

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
      Ah, thanks. This is not 100% what I wished for, but it certainly helps. And I notice there is also $^P=0x200 for the anonymous subroutine counterpart. Nice.
Re: Changing "filename" of eval-ed code
by Anonymous Monk on May 20, 2016 at 08:20 UTC

    #line

    string eval is baad, mmkay :p

      One good quote?
      Perl was not designed to stop you from doing stupid things, because that would also stop you from doing clever things. Plus nobody can stop you from doing stupid things.

      other arguments needed?

      Being my opinion not globally relevant, I ever considered eval a great gift: the compiler walk silently at your side; at any moment you can ask him what if I.. eval answer always adhere to the reality, ie the Perl compiler. Obviously at your own risk..

      L*

      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

      Not bad, just accompanied by a heightened level of risk and complexity. Manage those effectively, and it's a useful tool.


      Dave

      What is the alternative for dynamic code execution? require(), do()? They're basically the same thing as eval "", only more cumbersome :)