Search code examples
perl

How can I have one perl script call another and get the return results?


How can I have one perl script call another perl script and get the return results?

I have perl Script B, which does a lot of database work, prints out nothing, and simply exits with a 0 or a 3.

So I would like perl Script A call Script B and get its results. But when I call:

my $result = system("perl importOrig.pl filename=$filename");

or

my $result = system("/usr/bin/perl /var/www/cgi-bin/importOrig.pl filename=$filename");

I get back a -1, and Script B is never called.

I have debugged Script B, and when called manually there are no glitches.

So obviously I am making an error in my call above, and not sure what it is.


Solution

  • There are many things to consider.

    Zeroth, there's the perlipc docs for InterProcess Communication. What's the value in the error variable $!?

    First, use $^X, which is the path to the perl you are executing. Since subprocesses inherit your environment, you want to use the same perl so it doesn't confuse itself with PERL5LIB and so on.

    system("$^X /var/www/cgi-bin/importOrig.pl filename=$filename")
    

    Second, CGI programs tend to expect particular environment variables to be set, such as REQUEST_METHOD. Calling them as normal command-line programs often leaves out those things. Try running the program from the command line to see how it complains. Check that it gets the environment it wants. You might also check the permissions of the program to see if you (or whatever user runs the calling program) are allowed to read it (or its directory, etc). You say there are no glitches, so maybe that's not your particular problem. But, do the two environments match in all the ways they should?

    Third, consider making the second program a modulino. You could run it normally as a script from the command line, but you could also load it as a Perl library and use its features directly. This obviates all the IPC stuff. You could even fork so that stuff runs concurrently.