简体   繁体   English

如何引用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: 现在,我这样做:

External file 外部文件

package settingsGeneral;    
sub printScreen {
    print $_[0];
}

Main 主要

use settingsGeneral;    
my $printScreen = settingsGeneral::printScreen;
&$printScreen("test");

but this result into an error: Can't use string ("1") as a subroutine ref while "strict refs" in use 但这导致错误:不能使用字符串(“1”)作为子程序ref,而“strict refs”在使用中

As noted in perlmodlib , you should start your module's name with an uppercase letter: perlmodlib中所述 ,您应该使用大写字母开始模块的名称:

Perl informally reserves lowercase module names for 'pragma' modules like integer and strict . Perl非正式地保留了“pragma”模块的小写模块名称,如integerstrict 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";

If all you want is a reference to printScreen , grab it with the backslash operator 如果你想要的只是printScreen的引用, printScreen使用反斜杠操作符来获取它

my $subref = \&SettingsGeneral::printScreen;

and call it with one of 并用其中一个调用它

&$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");

Skip the parentheses (necessary because the sub in the current package wasn't known at compile time) by writing: 通过编写以下内容来跳过括号(必要,因为编译时未知当前包中的sub):

use subs 'printScreen';
*printScreen = \&SettingsGeneral::printScreen;
printScreen "the sky is falling!\n";

The Exporter module can do this custodial work for you: Exporter模块可以为您执行此保管工作:

SettingsGeneral.pm: SettingsGeneral.pm:

package SettingsGeneral;

use Exporter 'import';

our @EXPORT = qw/ printScreen /;

sub printScreen {
  print $_[0];
}

1;

main: 主要:

#! /usr/bin/perl

use warnings;
use strict;

use SettingsGeneral;

printScreen "foo!\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM