perl - 使用 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;
解决方案
- 您缺少
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";
推荐阅读
- python - 从字典列表中打印数据/值,而字典列表又包含列表和字典
- java - 在 Java 中为 println() 函数内的变量赋值是否有效?
- android - androidx ActivityResultContracts.RequestPermission 似乎在取消请求时有问题
- php - 字符串 PHP 中的数组元素:如何按字符串的顺序打印匹配的元素?
- javascript - 如何测试具有多个子组件的 React 组件?
- sql - 编写查询以打印一年中的最后一个日期,输入将是任何日期
- data-science - 在特征选择期间要删除哪些特征
- python - 为什么 python 不为其关联的 --hhelp 使用自己的 argparse 库?
- matlab - 如何并行运行代码?(通过VISA和RS232与设备通信
- javascript - rxjs 合并 http 响应