In Perl, how can I find out if my file is being used as a module or run as a script?

后端 未结 3 388
旧巷少年郎
旧巷少年郎 2020-12-10 05:04

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 mai

3条回答
  •  失恋的感觉
    2020-12-10 05:38

    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
    

提交回复
热议问题