bschmer has asked for the wisdom of the Perl Monks concerning the following question:

I've asked a similar question to this one before, but now I'm stuck at another junction and need some wisdom. What I'm trying to do is have a Perl module that is also usable standalone. Things are working just fine, except when it comes to passing arguments into the script. First, a little code:
#!/bin/sh eval "exec /usr/bin/perl -I`dirname $0` -M`basename $0 .pm` -e main -- + $@ " if $running_under_some_shell; sub main { for my $arg (@ARGV){ print "=>$arg<=\n"; } } 1;
When I run this script with arguments like "this is" "a test", I get
=>this is a test<=
when I want to get
=>this is<=
=>a test<=
I'm looking for any suggestions. I've found ways of making the shell handle things correctly, but Perl doesn't like any of the incantations that I've tried.

Replies are listed 'Best First'.
Re: Module/script all in one
by TomDLux (Vicar) on Jan 08, 2004 at 23:21 UTC

    You've got the right idea ... outside quotes, $* and $@ are the same, but within quotes, "$*" produces one argument, while "$@" produces $# arguments. (See my quick shell tutorial. However, you have an eval & an exec; the exec gets two arguments, but combines them into one while invoking Perl.

    But who cares about shell? This is Perl!

    In your module:

    if ( $0 eq __FILE__ ) { # Code to run when the module IS the program }

    --
    TTTATCGGTCGTTATATAGATGTTTGCA

•Re: Module/script all in one
by merlyn (Sage) on Jan 08, 2004 at 23:16 UTC
Re: Module/script all in one
by ysth (Canon) on Jan 09, 2004 at 05:24 UTC
    The usual way to have a module work as a script is to do something like:
    if (defined caller) { print "used as a module"; } else { print "used as a script: @ARGV"; main() }
    Is there more that you are trying to accomplish than that?
Re: Module/script all in one
by bschmer (Friar) on Jan 09, 2004 at 12:00 UTC
    Thanks all. I guess I was a little too engrained with the shell eval exec from my Camel book to think about a pure Perl solution to the problem. Shame on me! :-(