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

Hi Monks,

I've got a Perl script (script1.pl) which, amoung other things, does:

  do 'script2.pl';

script1.pl is called from a web browser to create a web page.

What are my options for passing a parameter to script2.pl?

I've tried things like:

  do 'script2.pl 123';

and

  do 'script2.pl&var1=123';

but they both don't work (they don't give an error message, but script2.pl doesn't get run).

Until now, I've been working around this by doing:

  our $var1 = 123;

before the 'do' command.  Is there a better way to pass a parameter to script2.pl with 'do'?

Thanks.

Replies are listed 'Best First'.
Re: do script2.pl with parms
by Corion (Patriarch) on Nov 12, 2010 at 08:33 UTC

    See system. It is different from do. Choose the one you need.

Re: do script2.pl with parms
by cosimo (Hermit) on Nov 12, 2010 at 09:39 UTC

    Using do to call one script from inside another is considered not very elegant. Anyway.

    #!/usr/bin/perl print "We're in script1 now\n"; @ARGV = ("super", "duper"); do('script2'); print "Back in script1\n";
    In script2.pl then:
    #!/usr/bin/perl print "\tNow we're in script2\n"; my ($arg1, $arg2) = @ARGV; print "\t- arg1: $arg1\n"; print "\t- arg2: $arg2\n"; print "\tscript2 ends\n";

    So, one way to do it is to use @ARGV, the array that contains the list of "command line" arguments.

      Add a (scope-limiting) block and local to that and @ARGV won't be damaged in script 1:

      # in script 1 { local @ARGV=(...); do('script2'); }

      But this is just an awful kludge.

      tel2, move (most of) the code of script 2 into a module. use that module in script 2 to get the existing behaviour. use that module also in script 1 to get the functions you need.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

        A sometimes used technique is to use caller to distinguish between command line invocation as a script and use as a module:

        package DualUseScript; ... return 1 if caller; # script "main" code
        True laziness is hard work
Re: do script2.pl with parms
by tel2 (Pilgrim) on Nov 12, 2010 at 22:36 UTC
    Thank you all, for your excellent (and respectful) answers, to a part-time Perler.
    Much appreciated.
Re: do script2.pl with parms
by tel2 (Pilgrim) on Nov 12, 2010 at 09:23 UTC

    Thanks Corion,

    I have used system() and `` before, but I think they start another process, is that right?

    As a result, would 'do' be more efficient, performance wise?  It doesn't start another process, does it?

      do does not start a new process. But not starting a second process has implications too. All global variables and modifications that script2 makes will be visible from within script1, which may lead to interesting and hard to debug problems.