http://www.perlmonks.org?node_id=244186


in reply to Possible to have a module act as a standalone??

while do-able, doing so makes life much more complicated for your users.

you want a module that can be run as a script, but the search paths for scripts (OS determined) and modules (Perl determined) are different. if it's in a place where it could be run as a script, then it can't be loaded as a module w/o hackery. ditto for the reverse, if it's in a place where it could be loaded as a module (use Foo;) then it's not in a place where it could be called as a script.

create a module Foo.pm in the usual place. write a small foo wrapper script to put in the OS's search path.

this doesn't stop you from placing the script code in the module. infact it's probably wise to do so.

# Foo.pm package Foo; ... sub foo { for (@_) { Foo->new($_)->blah->print; } } 1; #!/usr/bin/perl # Foo wrapper script use Foo; Foo::foo(@ARGV);

i can't see a way around having two files when you want to be able to do 'foo "blah"' from the command line and 'use Foo;' in perl.

Replies are listed 'Best First'.
Re: Re: Possible to have a module act as a standalone??
by thor (Priest) on Mar 19, 2003 at 06:20 UTC
    you want a module that can be run as a script, but the search paths for scripts (OS determined) and modules (Perl determined) are different. if it's in a place where it could be run as a script, then it can't be loaded as a module w/o hackery. ditto for the reverse, if it's in a place where it could be loaded as a module (use Foo;) then it's not in a place where it could be called as a script.
    Jigga-what? There is nothing saying that @INC and your PATH environment variable have to be disjoint. I'm not saying that it's a good idea to have overlap (nor am I saying that it's a bad idea; kinda titilating, actually), but you could put a new directory that is understood to contain such hybrid scripts at the end of both @INC and PATH:
    push @INC, "/path/to/hybrids" setenv PATH $PATH:/path/to/hybrids export PATH=$PATH:/path/to/hybrids ...
    You get the idea.

    thor