这是关于我之前的问题 Hold Subroutine response and set to variable in Perl
陈述Module::thesub("hello")
曾在Module.pm
工作但如果我将其移至main.pl
#!/usr/bin/perl
use strict;
use warnings;
use Module;
Module::thesub("hello");
#!/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
没有值。
我该如何解决这个问题?
答案 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,其中有很多帖子。