如何确定是否正在使用 caller 在 eval 内部调用子例程? [英] How can I determine if a subroutine is being called inside eval using caller?

查看:49
本文介绍了如何确定是否正在使用 caller 在 eval 内部调用子例程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在学习 Perl,我的任务是使用 caller 来确定是否正在从任何更高级别的 eval 调用子例程.我应该想出一些代码来测试它并打印 Yes 如果它来自 evalNo 如果它不是.我在网络上找不到任何关于如何使用 caller 的好例子,想知道是否有人对如何去做这件事有任何想法或建议.

I'm still learning Perl and I was tasked to use caller to determine if a subroutine is being called from an eval at any higher level. I am supposed to come up with some code to test this on and print Yes if its from an eval or No if its not. I cannot find any good examples on how to use caller on the web and was wondering if anyone had any ideas or suggestions on how to go about doing this.

推荐答案

您不应该为此使用 caller.参考 perlvar:

You shouldn't be using caller for this. Refer to 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)

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

And this is before we even bog the caller code down with a number of iterations over the call stack and running string functions against stack levels, assuming we'll write bug-free code for all edge cases, etc.

编写代码以使用调用者来确定这是一个核心功能的完整重新实现.这就像问,我如何使用标量来实现链表?"答案应该是使用数组",而不是这就是方法!"

Writing code to use caller to determine this is a complete re implementation of a core feature. It's like asking, "How do I use scalars to implement a linked list?" The answer should be "Use an array", not "Here's how!"

这篇关于如何确定是否正在使用 caller 在 eval 内部调用子例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆