程序意外报告“使用未初始化的值”

时间:2018-04-13 08:29:48

标签: perl module subroutine scalar

这是关于我之前的问题 Hold Subroutine response and set to variable in Perl

陈述Module::thesub("hello") 曾在Module.pm工作但如果我将其移至main.pl

则失败

main.pl

#!/usr/bin/perl

use strict;
use warnings;

use Module;

Module::thesub("hello");

Module.pm

#!/usr/bin/perl

use strict;
use warnings;

package Module;

sub thesub {
    state $stored;

    $stored = shift if @_;
    return $stored;
}

my $testvar = thesub();

print $testvar;

1;

我收到此错误

  

使用未初始化的值$testvar

表示变量$testvar没有值。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

在加载模块时,模块中的语句在use Module;处运行。那时thesub()仍未使用参数调用,并且$stored未定义。这就是$testvar在分配时获得的内容,并在打印时发出警告。

$testvar可以在主

中使用
use strict;
use warnings;
use Module;

Module::thesub("hello");

my $testvar = Module::thesub();

即使我不确定这个问题的目的是什么。

从模块中删除$testvar的分配和打印。请注意,您还需要在模块开头use feature 'state';启用feature pragma

关于您展示的模块的一些评论

  • 不需要#!/usr/bin/perl,因为通常不打算运行模块

  • package Module;通常是第一行

  • 虽然你有什么工作,但考虑将模块中的符号用于调用代码,以便它可以导入它们并简单地说thesub()。一种常见的方式是

    package Module;
    
    use warnings;
    use strict;
    
    use Exporter qw(import);
    our @EXPORT_OK = qw(thesub);
    
    sub thesub { ... }
    
    1;
    

    并在主

    use Module qw(thesub);
    
    thesub("hello");
    

    首先查看Exporter并搜索SO,其中有很多帖子。