运行:
$t = 3;
{
tie $t, 'Yep';
} # Expect $t to become untied here.
print $t;
package Yep;
sub TIESCALAR {
bless {}, 'Yep';
}
sub UNTIE {
print "UNTIE\n";
}
sub DESTROY {
print "DESTROY\n";
}
输出是:
Can't locate object method "FETCH" via package "Yep" at a.pl line 5.
DESTROY
预期的输出是:
DESTROY
3
我要
tie
变量 $t 仅适用于 tie
的范围内。位于。在范围之外,它的行为必须与 tie 之前相同。所以我包装tie
进入区 block 并期望 untie
将在到达 block 末尾时被调用(例如“本地”,其中值在 block 末尾恢复,但对于绑定(bind)变量,我希望行为恢复(untie $t
))。注意 $t
还没有超出范围。
最佳答案
Why is UNTIE not called when tied variable goes out of scope?
问为什么
UNTIE
变量超出范围时不调用与询问为什么 UNTIE
相同。不调用 DESTROY
叫做。好吧,那将毫无用处。有用的是在 untie
时调用的函数。被调用,这就是 UNTIE
是。如果您希望在
untie
时调用公共(public)代码被调用,当对象被销毁时,没有什么能阻止你。sub UNTIE { shift->_destructor(@_) }
sub DESTROY { shift->_destructor(@_) }
关于perl - 为什么变量仍然绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32949822/