首页 > 解决方案 > 使用 perl 模块并将变量传递到子例程的问题

问题描述

所以我是 perl 编程语言的新手,我想让自己熟悉创建、使用和将参数传递到模块中。我制作了一个 hello world 模块,它将 main.pl 测试程序中的两个字符串变量作为参数,一个是“hello”,另一个是“world”并将它们打印出来。每次我尝试运行 main.pl 时,我都会遇到错误,并且我花了很多天试图让这个原本简单的程序正常运行。

这是我的 main.pl 函数的代码:

use FindBin;
use lib $FindBin::Bin;
use test;
use strict;
my $firststring = "hello";
my $secondstring = "world";
test::printthing(\$firststring, \$secondstring);

这是我的 test.pm 模块的代码:

package test;

use strict

use Exporter;
our @ISA = qw/Exporter/;
our @EXPORT = qw/&main/;

sub printthing{
    my $firstword = $_[0];
    my $secondwork = $_[1];
    print"$firstword\n";
    print"$secondword\n";
}1;

标签: perlmodule

解决方案


  • 您缺少use strict模块中行尾的分号。
  • 您尝试导出main()子例程,但您的模块没有名为 的子例程main()
  • 您将对变量的引用传递给子例程,但在打印它们之前不要取消引用它们。

最后一点,您可以继续传递引用,但在打印之前取消引用。

test::printthing(\$firststring, \$secondstring);

# and then in the subroutine...

print"$$firstword\n";
print"$$secondword\n";

或者,您可以只传入变量并完全忽略引用。

test::printthing($firststring, $secondstring);

# and then in the subroutine...

print"$firstword\n";
print"$secondword\n";

推荐阅读