如何在Perl中编写subs的importer?

时间:2015-11-10 16:31:52

标签: perl import

我有以下代码:

#! /usr/bin/perl -T

{
  package MSG;
  use strict;
  use warnings;

  sub info
  {
    print STDERR join("\n", @_), "\n";
  }

  sub import
  {
    no strict 'refs';
    *{caller().'::info'} = \&info;
  }
}

{
  package main;
  use strict;
  use warnings;
  MSG->import;
#  sub info;

  info "a", "b";
}

如果sub info;包中没有main行,我会收到以下错误:

String found where operator expected 

我认为理由是here。当我添加该行时,代码按预期工作。但我不希望它出现在main包中。

如何将sub info;的内容移动到import包的MSG函数中?

1 个答案:

答案 0 :(得分:2)

大多数人使用Exporter

BEGIN {
  package MSG;

  use strict;
  use warnings;

  use Exporter qw( import );
  our @EXPORT = qw( info );

  sub info {
    print STDERR join("\n", @_), "\n";
  }
}

{
  use strict;
  use warnings;

  BEGIN { MSG->import; }

  info "a", "b";
}

BEGIN周围的import可确保在编译info之前导入符号。使用use会更加清晰,这可能会使用很小的变化。

BEGIN {
  package MSG;

  use strict;
  use warnings;

  use Exporter qw( import );
  our @EXPORT = qw( info );

  sub info {
    print STDERR join("\n", @_), "\n";
  }

  $INC{"MSG.pm"} = 1;
}

{
  use strict;
  use warnings;

  use MSG;

  info "a", "b";
}