如何重新定义内置 Perl 函数? [英] How do I redefine built-in Perl functions?

查看:60
本文介绍了如何重新定义内置 Perl 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做两件事:

在生产代码中,我想重新定义 open 命令以使我能够添加自动文件日志记录.我从事数据处理应用程序/流程的工作,作为其中的一部分,让用户准确了解正在处理的文件非常重要.如果他们使用的是旧版本的文件,他们找出的一种方法是通读正在处理的文件列表.

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.

我可以创建一个新的 sub 来执行此日志记录并返回一个文件指针,并在我的代码中使用它代替 open.

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.

如果我能重新定义 open 并使预先存在的代码受益于这种行为,那就太好了.我可以这样做吗?

It would be really nice if I could just redefine open and have pre-existing code benefit from this behavior. Can I do this?

在调试代码中,我想重新定义 printf 命令以插入注释以及指示生成该行的代码的书面输出.同样,我有一个 sub 可以选择执行此操作,但是转换我现有的代码很乏味.

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.

推荐答案

对于开放:这对我有用.

use 5.010;
use strict;
use warnings;
use subs 'open';
use Symbol qw<geniosym>;

sub open (*$;@) { 
    say "Opening $_[-1]";
    my ( $symb_arg ) = @_;
    my $symb;
    if ( defined $symb_arg ) { 
        no strict;
        my $caller = caller();
        $symb = \*{$symb_arg};
    }
    else { 
        $_[0] = geniosym;
    }
    given ( scalar @_ ) { 
        when ( 2 ) { return CORE::open( $symb // $_[0], $_[1] ); }
        when ( 3 ) { return CORE::open( $symb // $_[0], $_[1], $_[2] ); }
    }
    return $symb;
}

open PERL4_FH, '<', 'D:\temp\TMP24FB.sql';
open my $lex_fh, '<', 'D:\temp\TMP24FB.sql';

对于 Printf:您是否查看过这个问题?-> 如何连接 Perl 的打印?

For Printf: Did you check out this question? -> How can I hook into Perl’s print?

这篇关于如何重新定义内置 Perl 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆