我在弄清楚如何引用外部模块文件中的子例程时遇到了一些麻烦。现在,我正在这样做:
外部文件
package settingsGeneral;
sub printScreen {
print $_[0];
}
主要的
use settingsGeneral;
my $printScreen = settingsGeneral::printScreen;
&$printScreen("test");
但这会导致错误:
在使用“strict refs”时,不能将字符串(“1”)用作子例程 ref
最佳答案
如 perlmodlib 中所述,您应该以大写字母开头模块的名称:
Perl informally reserves lowercase module names for 'pragma' modules like
integer
andstrict
. Other modules normally begin with a capital letter and use mixed case with no underscores (need to be short and portable).
调用另一个包中定义的子的一种方法是在调用它时完全限定该子的名称:
SettingsGeneral::printScreen "important message\n";
如果您只想引用
printScreen
, 用反斜杠操作符抓取它my $subref = \&SettingsGeneral::printScreen;
并用其中之一调用它
&$subref("one\n");
&{$subref}("two\n");
$subref->("three\n");
您可以创建一个 alias在您当前的包裹中:
*printScreen = \&SettingsGeneral::printScreen;
printScreen("another urgent flash\n");
跳过括号(这是必要的,因为当前包中的子在编译时是未知的)通过编写:
use subs 'printScreen';
*printScreen = \&SettingsGeneral::printScreen;
printScreen "the sky is falling!\n";
Exporter模块可以为你做这个保管工作:
SettingsGeneral.pm:
package SettingsGeneral;
use Exporter 'import';
our @EXPORT = qw/ printScreen /;
sub printScreen {
print $_[0];
}
1;
主要:
#! /usr/bin/perl
use warnings;
use strict;
use SettingsGeneral;
printScreen "foo!\n";
关于perl - 如何引用 Perl 子例程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2585273/