在Perl中,如何确定我的文件是用作模块还是作为脚本运行? [英] In Perl, how can I find out if my file is being used as a module or run as a script?

查看:96
本文介绍了在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>);

但是我忘了情况如何.搜索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

输出:

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆