gpt4 book ai didi

perl - 为什么 `$@` 不可信?

转载 作者:行者123 更新时间:2023-12-04 00:03:40 25 4
gpt4 key购买 nike

我似乎记得信任 $@ 的值是不安全的。在 eval 之后.关于有机会设置的信号处理程序 $@在你看到它之前。我现在也太累太懒了,无法追查真正的原因。那么,为什么信任 $@ 不安全? ?

最佳答案

Try::Tiny perldoc 对 $@ 的问题进行了明确的讨论。 :

There are a number of issues with eval.

Clobbering $@

When you run an eval block and it succeeds, $@ will be cleared, potentially clobbering an error that is currently being caught.

This causes action at a distance, clearing previous errors your caller may have not yet handled.

$@ must be properly localized before invoking eval in order to avoid this issue.

More specifically, $@ is clobbered at the beginning of the eval, which also makes it impossible to capture the previous error before you die (for instance when making exception objects with error stacks).

For this reason try will actually set $@ to its previous value (before the localization) in the beginning of the eval block.

Localizing $@ silently masks errors

Inside an eval block die behaves sort of like:

sub die {
$@ = $_[0];
return_undef_from_eval();
}

This means that if you were polite and localized $@ you can't die in that scope, or your error will be discarded (printing "Something's wrong" instead).

The workaround is very ugly:

my $error = do {
local $@;
eval { ... };
$@;
};

...
die $error;

$@ might not be a true value

This code is wrong:

if ( $@ ) {
...
}

because due to the previous caveats it may have been unset.

$@ could also be an overloaded error object that evaluates to false, but that's asking for trouble anyway.

The classic failure mode is:

sub Object::DESTROY {
eval { ... }
}

eval {
my $obj = Object->new;

die "foo";
};

if ( $@ ) {

}

In this case since Object::DESTROY is not localizing $@ but still uses eval, it will set $@ to "".

The destructor is called when the stack is unwound, after die sets $@ to "foo at Foo.pm line 42\n", so by the time if ( $@ ) is evaluated it has been cleared by eval in the destructor.

The workaround for this is even uglier than the previous ones. Even though we can't save the value of $@ from code that doesn't localize, we can at least be sure the eval was aborted due to an error:

my $failed = not eval {
...

return 1;
};

This is because an eval that caught a die will always return a false value.

关于perl - 为什么 `$@` 不可信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3686857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com