perl – 如何使用调用者确定是否在eval中调用子例程?

前端之家收集整理的这篇文章主要介绍了perl – 如何使用调用者确定是否在eval中调用子例程?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我还在学习Perl,我的任务是使用调用者来确定是否从更高级别的eval调用子例程.我应该想出一些代码来测试它并打印是的,如果它来自评估或否则如果不是.我找不到任何关于如何在网络上使用来电者的好例子,并且想知道是否有人对如何做到这一点有任何想法或建议.

解决方法

你不应该使用调用者.参见 perlvar

$EXCEPTIONS_BEING_CAUGHT
$^S
Current state of the interpreter.

    $^S         State
    ---------   -------------------------------------
    undef       Parsing module,eval,or main program
    true (1)    Executing an eval
    false (0)   Otherwise

The first state may happen in $SIG{__DIE__} and $SIG{__WARN__} handlers.
The English name $EXCEPTIONS_BEING_CAUGHT is slightly misleading,because the
undef value does not indicate whether exceptions are being caught,since 
compilation of the main program does not catch exceptions.

This variable was added in Perl 5.004.

至于为什么:

C:\Users\user>perl -MBenchmark -E "timethese(20000000,{'caller' => sub {caller()},'$^S' => sub {$^S}})"
Benchmark: timing 20000000 iterations of $^S,caller...
       $^S:  0 wallclock secs ( 0.11 usr +  0.00 sys =  0.11 cpu) @ 183486238.53/s (n=20000000)
            (warning: too few iterations for a reliable count)
    caller:  1 wallclock secs ( 0.87 usr +  0.00 sys =  0.87 cpu) @ 22909507.45/s (n=20000000)

这是在我们甚至通过调用堆栈上的多次迭代以及针对堆栈级别运行字符串函数来调低调用代码之前,假设我们将为所有边缘情况编写无错误代码等.

编写代码以使用调用程序来确定这是核心功能的完整重新实现.这就像问“我如何使用标量实现链表?”答案应该是“使用数组”,而不是“这是怎么回事!”

猜你在找的Perl相关文章