如何引用Perl子例程? [英] How can I take a reference to a Perl subroutine?
问题描述
我在弄清楚如何对外部模块文件中的子例程进行引用时遇到了一些麻烦.现在,我正在这样做:
I'm having some trouble figuring out how to make a reference to a subroutine in an external module file. Right now, I'm doing this:
外部文件
package settingsGeneral;
sub printScreen {
print $_[0];
}
主要
use settingsGeneral;
my $printScreen = settingsGeneral::printScreen;
&$printScreen("test");
但是导致错误:
推荐答案
如 perlmodlib 中所述,则应以大写字母开头模块名称:
As noted in perlmodlib, you should start your module's name with an uppercase letter:
Perl非正式地为"pragma"模块(如
integer
和strict
)保留小写模块名称.其他模块通常以大写字母开头,并且使用不带下划线的混合大小写(需要简短且可移植).
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).
调用另一个程序包中定义的子程序的一种方法是在调用该子程序时完全限定该子程序的名称:
One way to call a sub defined in another package is to fully qualify that sub's name when you call it:
SettingsGeneral::printScreen "important message\n";
如果您只想引用printScreen
,请使用反斜杠运算符
If all you want is a reference to printScreen
, grab it with the backslash operator
my $subref = \&SettingsGeneral::printScreen;
并使用其中之一调用它
&$subref("one\n");
&{$subref}("two\n");
$subref->("three\n");
您可以在当前程序包中创建别名:>
You could create an alias in your current package:
*printScreen = \&SettingsGeneral::printScreen;
printScreen("another urgent flash\n");
跳过括号(这是必需的,因为当前包中的sub在编译时未知)
Skip the parentheses (necessary because the sub in the current package wasn't known at compile time) by writing:
use subs 'printScreen';
*printScreen = \&SettingsGeneral::printScreen;
printScreen "the sky is falling!\n";
导出器模块可以为您完成以下托管工作:
The Exporter module can do this custodial work for you:
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子例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!