在 Perl 中,如何确定我的文件是否被用作模块或作为脚本运行?

发布于 2024-07-27 05:46:48 字数 245 浏览 6 评论 0原文

假设我有一个 Perl 文件,其中的某些部分仅在作为脚本调用时才需要运行。 我记得之前读过有关将这些部分包含在 main() 方法中并执行 a

main() unless(<some condition which tests if I'm being used as a module>);

但我忘记了条件是什么。 谷歌搜索并没有取得任何成果。 有人可以指出寻找此内容的正确位置吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

今天小雨转甜 2024-08-03 05:46:48

如果该文件作为脚本调用,则不会有 调用者,因此您可以使用:

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\n" }

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

If the file is invoked as a script, there will be no caller so you can use:

main() unless caller;

See brian d foy's explanation.

#!/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\n" }

no warnings 'void';
"MyClass"

Output:

C:\Temp> perl MyClass.pm
Hello World

Using from another script:

C:\Temp\> cat mytest.pl
#!/usr/bin/perl

use strict;
use warnings;

use MyClass;

my $obj = MyClass->new;
$obj->hello;

Output:

C:\Temp> mytest.pl
Hello World
冷清清 2024-08-03 05:46:48

我最初在我的脚本作为模块文章中将这些东西称为“modulinos” Perl Journal(现在的Dobbs 博士)。 谷歌这个词,你会得到正确的资源。 Sinan 已经链接到我的一本书中的开发资源,我在其中谈到了它。 您可能还喜欢脚本如何成为模块

I call these things "modulinos" originally in my Scripts as Modules article for The Perl Journal (now Dr. Dobbs). Google that term and you get the right resources. Sinan already linked to my development sources for one of my books where I talk about it. You might also like How a Script Becomes a Module.

红颜悴 2024-08-03 05:46:48

最好不要这样做,而是采用结构化方法,例如 MooseX::Runnable

您的类将如下所示:

class Get::Me::Data with (MooseX::Runnable, MooseX::Getopt) {

    has 'dsn' => (
        is            => 'ro',
        isa           => 'Str',
        documentation => 'Database to connect to',
    );

    has 'database' => (
        is         => 'ro',
        traits     => ['NoGetopt'],
        lazy_build => 1,
    );

    method _build_database {
        Database->connect($self->dsn);
    }

    method get_data(Str $for_person){
        return $database->search({ person => $for_person });
    }

    method run(Str $for_person?) {
        if(!$defined $for_person){
            print "Type the person you are looking for: ";
            $for_person = <>;
            chomp $for_person;
        }

        my @data = $self->get_data($for_person);

        if(!@data){
            say "No data found for $for_person";
            return 1;
        }

        for my $data (@data){
            say $data->format;
        }

        return 0;
    }
}

现在您有一个可以在程序中轻松使用的类:

my $finder = Get::Me::Data->new( database => $dbh );
$finder->get_data('jrockway');

在比上面的“run”方法更大的交互式脚本中:

...
my $finder = Get::Me::Data->new( dsn => 'person_database' );
$finder->run('jrockway') and die 'Failure'; # and because "0" is success
say "All done with Get::Me::Data.";
...

如果您只想独立执行此操作,您可以说:

$ mx-run Get::Me::Data --help
Usage: mx-run ... [arguments]
    --dsn     Database to connect to

$ mx-run Get::Me::Data --dsn person_database
Type the person you are looking for: jrockway
<data>

$ mx-run Get::Me::Data --dsn person_database jrockway
<data>

注意您编写的代码有多少,以及生成的类有多灵活。 “main if !caller”很好,但是当你可以做得更好时为什么还要麻烦呢?

(顺便说一句,MX::Runnable 有插件;因此您可以轻松增加看到的调试输出量、在代码更改时重新启动应用程序、使应用程序持久化、在分析器中运行它等)

Better to not do this, and instead take a structured approach like MooseX::Runnable.

Your class will look like:

class Get::Me::Data with (MooseX::Runnable, MooseX::Getopt) {

    has 'dsn' => (
        is            => 'ro',
        isa           => 'Str',
        documentation => 'Database to connect to',
    );

    has 'database' => (
        is         => 'ro',
        traits     => ['NoGetopt'],
        lazy_build => 1,
    );

    method _build_database {
        Database->connect($self->dsn);
    }

    method get_data(Str $for_person){
        return $database->search({ person => $for_person });
    }

    method run(Str $for_person?) {
        if(!$defined $for_person){
            print "Type the person you are looking for: ";
            $for_person = <>;
            chomp $for_person;
        }

        my @data = $self->get_data($for_person);

        if(!@data){
            say "No data found for $for_person";
            return 1;
        }

        for my $data (@data){
            say $data->format;
        }

        return 0;
    }
}

Now you have a class that can be used inside your program easily:

my $finder = Get::Me::Data->new( database => $dbh );
$finder->get_data('jrockway');

Inside an interactive script that is bigger than just the "run" method above:

...
my $finder = Get::Me::Data->new( dsn => 'person_database' );
$finder->run('jrockway') and die 'Failure'; # and because "0" is success
say "All done with Get::Me::Data.";
...

If you just want to do this standalone, you can say:

$ mx-run Get::Me::Data --help
Usage: mx-run ... [arguments]
    --dsn     Database to connect to

$ mx-run Get::Me::Data --dsn person_database
Type the person you are looking for: jrockway
<data>

$ mx-run Get::Me::Data --dsn person_database jrockway
<data>

Notice how little code you wrote, and how flexible the resulting class is. "main if !caller" is nice, but why bother when you can do better?

(BTW, MX::Runnable has plugins; so you can easily increase the amount of debugging output you see, restart your app when the code changes, make the app persistent, run it in the profiler, etc.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文