如何重新定义“开放”? 正确地使用 Perl 吗?
前段时间,我问了一个问题: How do I redefinebuilt in Perl功能?
答案对我很有帮助。 我有一个包可以覆盖 Perl 的“打开”功能,使我能够记录文件访问。
现在我遇到了一个破坏原始代码功能的案例。
use strict;
use warnings;
use Data::Dumper;
sub myopen (*;@) {
my $p;
my $retval = CORE::open($p, $_[1]);
{
no strict;
*{"main::$_[0]"} = $p;
}
return $retval;
}
BEGIN {
*CORE::GLOBAL::open = *myopen;
};
my @a = (1, 2, 3);
open(CHECK, ">dump") or print "UNABLE TO OPEN DUMPER FILE: $!\n";
print CHECK "test\n";
print CHECK Data::Dumper->Dump(\@a);
close CHECK
现在我收到此消息:
Can't locate object method "CHECK" via package "Data::Dumper"
我该如何解决它?
Some time ago, I ask a question: How do I redefine built in Perl functions?
And the answers have served me well. I have a package that overrides Perl's 'open' function enabling me to log file access.
Now I've come to a case that breaks the functionality of the original code.
use strict;
use warnings;
use Data::Dumper;
sub myopen (*;@) {
my $p;
my $retval = CORE::open($p, $_[1]);
{
no strict;
*{"main::$_[0]"} = $p;
}
return $retval;
}
BEGIN {
*CORE::GLOBAL::open = *myopen;
};
my @a = (1, 2, 3);
open(CHECK, ">dump") or print "UNABLE TO OPEN DUMPER FILE: $!\n";
print CHECK "test\n";
print CHECK Data::Dumper->Dump(\@a);
close CHECK
Now I get this message:
Can't locate object method "CHECK" via package "Data::Dumper"
How do I fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用“CHECK”以外的名称。
“CHECK”是一个在编译时调用的特殊函数,您确实不应该使用它。
为什么会出现这个特定错误?
另外,您使用的是全局文件句柄,这是有问题的。
使用这个符号:
这些额外的好处是当它们超出范围时它们会自动关闭。
Try using a name other than "CHECK".
"CHECK" is a special function which is called during compile time, and you really shouldn't use it.
Why that specific error?
Also, you're using global file handles, which are problematic.
use this notation:
These are extra beneficial is they self-close when they go out of scope.
比较:
我
使用了与“STDOUT”不同的名称,因为当它不是内置句柄时,它似乎只会使间接对象出错。
Compare:
to
I used a different name from "STDOUT" because it seems to only gets the indirect object wrong when it's not a built-in handle.
这将起作用并且不会产生错误...
这会阻止它被混淆有一个 “间接对象语法”
但是,我建议避免使用 CHECK 和其他 Perl 中的特殊命名代码块 和使用文件句柄的词法变量是首选方法。 PBP
This will work and without producing the error...
This stops it being confused has an "Indirect Object Syntax"
However I do recommend steering clear of using CHECK and other special named code blocks in Perl and using lexical variables for filehandles is the preferred method. PBP