在 Perl 中,如何确定我的文件是作为模块使用还是作为脚本运行? [英] In Perl, how can I find out if my file is being used as a module or run as a script?
本文介绍了在 Perl 中,如何确定我的文件是作为模块使用还是作为脚本运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个 Perl 文件,其中只有当我作为脚本调用时才需要运行的部分.我记得有一段时间读过关于将这些部分包含在 main() 方法中并执行
Let's say I have a Perl file in which there are parts I need to run only when I'm called as a script. I remember reading sometime back about including those parts in a main() method and doing a
main() unless(<some condition which tests if I'm being used as a module>);
但我忘记了条件是什么.搜索谷歌并没有产生任何结果.有人可以指出寻找这个的正确位置吗?
But I forgot what the condition was. Searching Google hasn't turned out anything fruitful. Can someone point out the right place to look for this?
推荐答案
如果将文件作为脚本调用,将不会出现 调用者 所以你可以使用:
If the file is invoked as a script, there will be no caller so you can use:
main() unless caller;
请参阅 brian d foy 的 说明.
#!/usr/bin/perl
use strict;
use warnings;
main() unless caller;
sub main {
my $obj = MyClass->new;
$obj->hello;
}
package MyClass;
use strict;
use warnings;
sub new { bless {} => shift };
sub hello { print "Hello World
" }
no warnings 'void';
"MyClass"
输出:
C:Temp> perl MyClass.pm
Hello World
从另一个脚本使用:
C:Temp> cat mytest.pl
#!/usr/bin/perl
use strict;
use warnings;
use MyClass;
my $obj = MyClass->new;
$obj->hello;
输出:
C:Temp> mytest.pl
Hello World
这篇关于在 Perl 中,如何确定我的文件是作为模块使用还是作为脚本运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文