为什么在使用eval之前需要本地化$ @? [英] Why do I need to localize $@ before using eval?

查看:80
本文介绍了为什么在使用eval之前需要本地化$ @?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 $ @ 是一个全局变量的事实,但是我仍然不知道为什么在使用评估

I'm aware of the fact that $@ is a global variable, still I can't figure out why I need to localize it before using eval:

例如:

eval { SOME_FUNC_THAT_MAY_DIE(); };
if ($@) {
  print "An error occured!\n";
}

我唯一想到的可能是,如果某些信号处理程序将调用 die 同时尝试读取 $ @ ,我在这里想念什么?

The only possible thing I can think of is, if some signal handler will call die at the same time I try to read $@, what am I missing here?

推荐答案

在调用 eval之前说 local $ @ 的原因是为了避免踩到呼叫者的 $ @ 。子例程更改任何全局变量是不礼貌的(除非这是该子例程的既定目的之一)。

The reason to say local $@ before calling eval is to avoid stepping on your caller's $@. It's rude for a subroutine to alter any global variables (unless that's one of the stated purposes of the subroutine). This isn't really an issue with top-level code (not inside any subroutine).

此外,在较旧的Perl上,任何 eval

Also, on older Perl's, any eval called during object destruction would clobber the global $@ (if the object was being destroyed because an exception was being thrown from an eval block) unless $@ was localized first. This was fixed in 5.14.0, but many people are still running older Perls.

这篇关于为什么在使用eval之前需要本地化$ @?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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