【问题标题】:same warning multiple times when package in @ISA is not loaded未加载 @ISA 中的包时多次发出相同警告
【发布时间】:2013-12-11 02:41:27
【问题描述】:

在重构我的一些 perl 代码时,我 注意到以下奇怪的行为。
考虑这个小示例脚本:

#!/usr/bin/perl -w

package test;
use strict;
my $obj = bless( {}, __PACKAGE__);
our @ISA = qw( missing );

exit(0)

预期警告

Can't locate package missing for @test::ISA at test.pl line 8

出现 3 次而不是仅 1 次。此警告的其他两个触发器是什么?这三个都指exit(0)
gentoo linux 上的 perl 版本 5.12.4。

谢谢。

【问题讨论】:

  • @missing::ISA, &missing::DESTROY 是两个可能的候选者。甚至可能 &missing::AUTOLOAD...
  • 在 perl 5.16 之前只有三个警告。在 perl 5.18 中只有两个警告。

标签: perl perl-module


【解决方案1】:

我相信 tjd 得到了答案。如果您在测试包中添加 DESTROY() 和 AUTOLOAD() 方法,您只会收到一个警告(关于缺少 @test::ISA)。

   package test;
   use strict;

   sub DESTROY {}
   sub AUTOLOAD {}

您通常需要确保@ISA 列表中列出的包已经被加载。在您的示例中,您可能希望看到如下内容:

   package test;  
   use strict;
   use missing;

   our @ISA = ('missing');

你的包没有明确的 new() 方法有点奇怪。相反,您有一个调用 bless();

的语句

如果你有一个 new() 方法,像这样:

   sub new() { return bless {}, __PACKAGE__; }

然后你不会看到三重错误消息,直到调用 new();

   package main;
   my $object = test->new(); # Triple warning

您可能想要使用 pragma 'base',这会给您一个致命错误,说它无法加载 'missing' 包:

   package test; 
   use strict;
   use base ('missing');

   sub new { bless {}, __PACKAGE__);

基本编译指示会尝试为您加载丢失的包。您不需要单独的“使用缺失”语句。

所以最后的结果可能是这样的:

   package test;
   use strict;
   use warning;
   use base ('missing');

   sub new { bless {}, __PACKAGE__);
   sub DESTROY {}
   sub AUTOLOAD {}
   1;

然后您可以将这一切包装到一个名为 test.pm 的文件中并在脚本中使用它:

   use strict;
   use test;

   my $object = test->new(); # Should fatal, as there is no 'missing' module

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多