如何重新定义内置 Perl 函数?
我想做两件事:
在生产代码中,我想重新定义 open 命令以使我能够添加自动文件日志记录。 我致力于数据处理应用程序/流程,作为其中的一部分,用户准确了解正在处理哪些文件非常重要。 如果他们使用的是旧版本的文件,他们找出问题的一种方法是阅读正在处理的文件列表。
我可以创建一个新的 sub 来执行此日志记录并返回一个文件指针,并在我的代码中使用它来代替 open 。
如果我可以重新定义 open 并使预先存在的代码从这种行为中受益,那就太好了。 我可以这样做吗?
在调试代码中,我想重新定义 printf 命令以插入注释以及指示哪个代码生成该行的书面输出。 同样,我有一个子可以选择执行此操作,但转换我现有的代码很乏味。
I want to do two things:
In production code, I want to redefine the open command to enable me to add automagic file logging. I work on data processing applications/flows and as part of that, it's important for the user to know exactly what files are being processed. If they are using an old version of a file, one way for them to find out is by reading through the list of files being processed.
I could just create a new sub that does this logging and returns a file pointer and use that in place of open in my code.
It would be really nice if I could just redefine open and have pre-existing code benefit from this behavior. Can I do this?
In debug code, I'd like to redefine the printf command to insert comments along with the written output indicating which code generated that line. Again, I have a sub that will optionally do this, but converting my existing code is tedious.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果 CORE 子例程有原型
*
,则可以替换它。 替换当前命名空间中的函数非常简单。如果您还想覆盖所有模块的函数,您可以阅读文档。
*
下面是测试 Perl 5.10 中每个函数的代码(它也适用于早期版本)。 请注意,某些函数可以被覆盖,该程序会告诉您不能,但被覆盖的函数的行为方式将与原始函数不同。来自 perldoc -f 原型
If a CORE subroutine has a prototype
*
it can be replaced. Replacing a function in the current namespace is simple enough.If you want to override the function for all modules as well you can read the docs.
*
Here is code to test every function in Perl 5.10 (it will work on earlier versions as well). Note, some functions can be overridden that this program will tell you can't be, but the overridden function will not behave in the same way as the original function.from perldoc -f prototype
对于开放:这对我有用。
对于Printf:您检查过这个问题吗? -> 如何挂钩 Perl 的打印?
For open: This worked for me.
For Printf: Did you check out this question? -> How can I hook into Perl’s print?