在Perl中,如何确定我的文件是用作模块还是作为脚本运行? [英] In Perl, how can I find out if my file is being used as a module or run as a script?
问题描述
比方说,我有一个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>);
但是我忘了情况如何.搜索Google并没有取得任何成果.有人可以指出寻找这个地方的正确位置吗?
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 的
输出: 使用其他脚本: 输出: 这篇关于在Perl中,如何确定我的文件是用作模块还是作为脚本运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!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