What does 1 inside eval body mean in perl?

huangapple go评论57阅读模式
英文:

What does 1 inside eval body mean in perl?

问题

在Perl中,eval块中的1表示eval块的结果为真。这通常用于表示eval块成功执行,没有发生错误。在eval块中,最后一个表达式的值用于确定eval块的结果,如果该值为真,Perl会认为eval块成功,没有遇到错误。因此,这里的1用于指示没有错误发生。

并不强制要求在eval块的末尾指定任何特定的值,但通常使用1表示成功或没有错误。如果在eval块中发生了错误,通常会返回false值,以便在or do { #handle Error Gracefully }部分处理错误情况。

英文:

What does 1 inside the eval block in perl mean?
see the sample code:

eval { 
    print "Ajay";
    1;
} or do { 
    #handle Error Gracefully 
}

Do we tell perl runtime that there was no error that we encountered in the eval block by specifying some positive value at the end of the block?

Or Is it mandatory to specify something at the end?

答案1

得分: 3

两个句法结构 eval BLOCKdo BLOCK 基本上执行相同的操作:它们都执行其块并返回该块中最近评估的表达式的结果。区别在于 do 可能根本不返回,而 eval 总是会返回。

do 可能不返回的原因是其块正在执行的代码可能会引发异常。这会“抛出一个异常”(不是错误,而是异常),将您的执行过程迅速传送到第一个动态封闭的异常处理程序。

相比之下,如果在执行 eval 过程中,其中的代码“失败”(即发生某个异常),而不是 eval 自己失败,eval 将立即返回 undef 并将全局 $@ 变量设置为导致其失败的异常。

因此,在您的 eval 块末尾的 1; 保证了它无论 print 语句本身是否成功都会返回1。print 运算符成功返回1,出错返回0,并设置全局 $! 变量以包含错误。它不会引发异常。因此,如果 print 失败,那么如果您只是像 or 这样的逻辑运算符那样检查它是否为真或假,那么没有那个 1;eval 本身将似乎已经失败了。

这样做没有任何理由,因为 print 不会引发异常。

英文:

The two syntactic constructions eval BLOCK and do BLOCK do almost the same thing: both execute their block and return the result of the most recently evaluated expression from that block. The difference is that do might not return at all, whereas eval will always do so.

The reason do might not return is that the code its block is executing might die. That "throws an exception" (not an error, but an exception) that teleports your execution way up the stack to the first dynamically enclosing exception handler.

In contrast, if in the course of executing the eval, the code within it "dies" (read: some exception occurs) rather than itself dying, the eval immediately returns undef and sets the global $@ variable to the exception that made it die.

So that 1; at the end of your eval block guarantees that it returns 1 no matter whether the print statement itself does so. The print operator returns 1 on success and 0 on error, setting the global $! variable to contain the error. It does not die. So if the print failed, then without that 1; the eval itself would appear to have failed if you're only checking it for true or false the way the logical operators like or do.

There is no reason to do this, because print does not throw exceptions.

huangapple
  • 本文由 发表于 2023年7月3日 22:08:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76605555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定