Search code examples
perlmodulemodulino

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


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?


Solution

  • 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