代码之家  ›  专栏  ›  技术社区  ›  Colin Fine

如何在Perl中重命名导出的函数?

  •  2
  • Colin Fine  · 技术社区  · 16 年前

    我有一些导出各种函数的Perl模块。(我们已经有几年没有在新模块中使用@EXPORT了,但为了与旧脚本兼容,我们保留了它。)

    *directory_error      = *directoryError;
    

    在模块的末尾,只需将旧名称别名为新名称。

    除非导出旧名称,并且调用脚本使用非限定名称调用函数:在这种情况下,它报告未找到子例程(在调用模块中)。

    有什么好的处理方法的建议吗?

    3 回复  |  直到 16 年前
        1
  •  2
  •   Community CDub    5 年前

    出口

    package Bar;
    use strict;
    use warnings;
    
    use Sub::Exporter -setup => {
        exports => [qw[ foo ]],
        groups  => {
            default => [qw[ foo ]],
        }
    };
    
    sub foo(){
    
    };
    
    
    1;
    

    使用:

    use strict;
    use warnings;
    use Bar  foo => { -as-> 'Foo' }; 
    

    Sub::Exporter可以做很多很棒的事情,比如组导出、组排除、构建器方法(即:它导出的Sub的工作方式是由传递的参数决定的,Sub是在其他Sub内部生成的,等等)

    更名

    对于重命名对象,最好使用一个二级函数,该函数在调用Carp()时作为遗留函数,以推荐在任何地方指向它的代码移动到新方法。这将提高代码范围内的一致性。

    然后,当测试停止发出警告时,可以删除遗留函数。

    sub old {  # line 1
       Carp::carp('Legacy function \'old\' called, please move to \'newmethod\' '); 
       goto &newmethod; # this passes @_ literally and hides itself from the stack trace. 
    } # line 4
    
    sub newmethod { # line 6
       Carp::cluck('In New Method'); 
       return 5;
    } # line 9
    
    print old(), "\n";  # line 11
    
    Legacy function 'old' called, please move to 'newmethod' at code.pl line 2
        main::old() called at code.pl line 11
    In New Method at code.pl line 7
        main::newmethod() called at code.pl line 11
    5
    

        2
  •  1
  •   Michael Carman    16 年前

    以下内容适合我。这似乎就是你所描述的;你一定是在什么地方出错了。

    主脚本:

    use strict;
    use warnings;
    use Bar;
    
    baz();
    

    模块:

    package Bar;
    use strict;
    use warnings;
    
    require Exporter;
    our @ISA    = qw(Exporter);
    our @EXPORT = qw(baz);
    
    sub Baz { print "Baz() here\n" }
    
    *baz = *Baz;
    
    1;
    
        3
  •  0
  •   Chas. Owens    16 年前

    如果希望两个名称都可见,则必须同时导出这两个名称。以迈克尔·卡曼的答案为基础,你需要

    our @EXPORT = qw(Baz baz);
    

    our @EXPORT    = qw(Baz);
    our @EXPORT_OK = qw(baz);
    

    推荐文章