如何在Perl中编写subs的importer? [英] How to write an importer for subs in Perl?

查看:157
本文介绍了如何在Perl中编写subs的importer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

#! /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";
}

没有子信息; main 包中的行,我收到以下错误:

Without the sub info; line in the main package, I get the following error:


String found where operator expected 

我认为原因在于解释此处。当我添加该行时,代码按预期工作。但是我不希望它出现在 main 包中。

I think the reason is explained here. When I add the line, the code works as expected. But I do not want it in the main package.

如何移动任何子info; 进入导入函数的 MSG 包?

How to move whatever sub info; does into the import function of the MSG package?

推荐答案

大多数人使用 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 之前导入符号。使用使用会更干净,这可以使用小的改动。

The BEGIN around import ensures the symbol is imported before info is compiled. It would be cleaner to use use, which is possible using small change.

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";
}

这篇关于如何在Perl中编写subs的importer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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