【问题标题】:Using modules with Perl在 Perl 中使用模块
【发布时间】:2014-02-28 17:09:44
【问题描述】:

我正在尝试为我的示波器制作一个函数库,但我似乎无法让其他模块文件发挥得很好。

除了Oscope.pm 文件外,我所拥有的都在这里。如果需要,我也可以上传。

test.pl

# Includes
use 5.012;
use Oscope;
use Oscope::Acquire;
use warnings;

# From Oscope.pm
my $scope = Oscope->new('port', 'COM3');

# From Oscope::Acquire.pm
$scope->QueryAcquire();

Oscope/Acquire.pm

package Oscope::Acquire;

use Oscope;
use parent 'Oscope';

sub QueryAcquire
{
   my ($self) = @_;
   # Oscope.pm
   my $message = $self->Send('ACQUIRE?');
   return();
}

1;

输出

无法通过包“Oscope”在 C:\Documents and Settings\ericfoss\My Documents\Slick\Perl\tests\Test.pl 第 11 行找到对象方法“QueryAcquire”。

【问题讨论】:

  • 你想做的有点超出主流。通过Perl 的monkeypatching 形式可能的,但它不会很漂亮。简单地从Oscope 继承或制作带有Oscope 参数的函数更为常见。

标签: perl oop perl-module


【解决方案1】:
Oscope->new('port', 'COM3')

应该是

Oscope::Acquire->new('port', 'COM3')

【讨论】:

  • 也就是说,我不相信继承在这里是合适的。
  • 是的,这是互联网上的常见示例,但我想用新功能扩展 Oscope 对象。也许我完全不喜欢这个父/基础的东西。
  • @EricFossum:最好退后一步,描述一下您想要实现的目标。显示您知道不遵守文档的代码并询问它为什么不起作用是不诚实的。
【解决方案2】:

我不会说这是个好主意。您显然希望 Oscope::Aquire 到猴子补丁 Oscope。这是可能的,但我建议让Oscope::Acquire 导出一个带有Oscope 参数的函数(more information on exporting):

Oscope/Acquire.pm

package Oscope::Acquire;
require Exporter 'import';
@EXPORT_OK = qw{QueryAcquire};

use Oscope;

sub QueryAcquire
{
    my ($oscope) = @_;
    my $message = $oscope->Send('ACQUIRE?');
    return $message;
}

1;

你会使用哪个:

use Oscope;
use Oscope::Acquire 'QueryAcquire';

my $oscope = Oscope->new();
print QueryAquire($oscope);

但是,如果您真的想要 $oscope->QueryAcquire() 语法,并且不想将其放入 Oscope 本身,您可以对模块进行猴子补丁。 Perl 文档将此称为 modifying the module's symbol table through a typeglob 并且它显然已被弃用(“直接创建新符号表条目的结果......未定义并且可能在 perl 版本之间发生变化”):

Oscope/Acquire.pm

package Oscope::Acquire;

use Oscope;

*Oscope::QueryAcquire = sub {
    my ($self) = @_;
    my $message = $self->Send('ACQUIRE?');
    return $message;
}

1;

我应该更仔细地阅读我自己的链接。看来,批准的做法是简单地将方法添加到 Oscope/Acquire.pm 文件内的 Oscope 包中(“您可以通过显式限定子例程的名称来定义其包之外的子例程”):

package Oscope::Acquire;
use Oscope;

...

sub Oscope::QueryAcquire {
    my ($self) = @_;
    my $message = $self->Send('ACQUIRE?');
    return $message;
}

1;

也就是说,不需要 typeglob。

【讨论】:

  • 感谢您提供的信息,正是我所需要的。另外,我不敢相信猴子补丁是一个技术术语(感谢 Perl 社区)。
  • 我不确定是谁提出了“猴子补丁”这个词。我认为它在 Perl 中不如其他一些语言常见。
【解决方案3】:

你的 lib 包在哪里,把你的代码放在那里。你也可以使用

use lib "path"

可以在here 找到另一个解释,其中答案需要 lib。

您的区域消息说明了它无法找到该功能。

【讨论】:

    【解决方案4】:

    就代码而言,您可以直接说$scope->Oscope::Acquire::QueryAcquire();,但要获得预期的效果,您需要将其作为包的一部分。

    package Oscope;
    
    sub QueryAcquire
    {
       # Code here
    }
    
    1;
    

    【讨论】:

      猜你喜欢
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 2013-10-08
      • 2012-05-18
      相关资源
      最近更新 更多