Override "eval" in perl

Having the following:

use 5.014; use warnings; BEGIN { use subs qw(int); sub int { print STDERR "\tthe int got: $_[0]\n"; my $res = CORE::int($_[0]); print STDERR "\tCORE::int: $res\n"; return $res; } } my $x; $x = 1.1 ; say "result of int($x) is: ", int($x); $x = 6.6 ; say "result of int($x) is: ", int($x); 

he prints

  the int got: 1.1 CORE::int: 1 result of int(1.1) is: 1 the int got: 6.6 CORE::int: 6 result of int(6.6) is: 6 

The int function is overridden by my own function, which performs some debugging prints and returns the result of the original (CORE) implementation.

Look for the same for eval . But probably because eval not a function like int , overriding, as mentioned above, does not work for eval.

Can this be achieved somewhat? For example. want to override eval ( eval "$string" ) with my own rating as above, like this:

  • should print the received string
  • and should call the main implementation of eval

EDIT: According to the comments, this is not possible for eval . So:

In short: before debugging, I want to debug printing all eval "$strings" in my program. Maybe a few?

+7
perl
source share
1 answer

eval cannot be overridden in the same way as int , since its interface cannot be prototyped.

 $ perl -E'say prototype("CORE::".$ARGV[0]) // "[undef]"' int _ $ perl -E'say prototype("CORE::".$ARGV[0]) // "[undef]"' eval [undef] 

But there is good news! Someone had similar needs, solved it by manipulating the operation code, and published a solution for CPAN in the form of overload :: eval for anyone who can use it.

The documentation claims that it only affects eval in the lexical scope of use , but there is a hidden flag $overload::eval::GLOBAL = 1; , which affects all calls to eval EXPR .

+5
source share

All Articles