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

I have a CGI script.
I need it to call another Perl program.
That second Perl program will be expecting a hash for input. It will then do 'stuff' and end up with a new hash to be sent back to the first program.
I'm new to the whole IPC conecpt, other than basic system calls. Can anyone out there offer some clear-cut info on how to do this sort of thing?

Replies are listed 'Best First'.
Re: Calls to other Perl programs
by etcshadow (Priest) on Oct 09, 2003 at 22:52 UTC
    First of all... is there any reason this should be calling a second program, as opposed to a subroutine? If not, see the first comment in this thread.

    If this actually does have to be done via some sort of interprocess communication, the easiest way is to serialize the input hash for the command line, and to serialize the output hash to STDOUT. It looks something like this... starting with the calling script:

    my %input_hash = ( ... ); # serialize your hash my $arguments = Dumper \%input_hash; # this is how to escape an arbitrary string for the unix shell $arguments =~ s/'/'\\''/g; $arguments = "'$arguments'"; my $resultstring = `perl my_other_script.pl $arguments`; my %result_hash = %{eval $resultstring};
    and the called script would do this:
    use Data::Dumper my %input_hash = %{eval $ARGV[0]}; # do stuff... don't print anything! print Dumper \%result_hash; exit;
    Of course, this is dependant on being run on unix for the shell-escaping. If this were being run on a different system, you would need to escape the command-line appropriately. If you wanted this to be truly cross-platform, though, you'd have to pipe in the input string, which would require you to use IPC::open2 (allows you to create both a pipe in and a pipe out of a process... backticks are only a pipe out, but are simpler to use).

    ------------
    :Wq
    Not an editor command: Wq
Re: Calls to other Perl programs
by BUU (Prior) on Oct 09, 2003 at 17:00 UTC
    cgi.pl
    use strict; use MyMod; my %hash = ( usual=>'stuff',so=>'on',foo=>'bar' ); %hash = MyMod->do_stuff(%hash);

    MyMod.pm
    package MyMod; use strict; sub do_stuff { shift; my %newhash=@_; #stuff return %newhash; }