1

Is there a perl function, either built in, or in a library that is like the following:

run(IN_FILEHANDLE, OUT_FILEHANDLE, ERR_FILEHANDLE, $cmd);

Which gets the external command to read from IN_FILEHANDLE, write to OUT_FILEHANLE, with stderr going to ERR_FILEHANDLE.

e.g.

run(STDIN, STDOUT, STDERR, $cmd);

Will be similar to:

system($cmd);

And:

run(IN, OUT, ERR, $cmd);

Will be a bit like a non-existant version of:

open(IN, OUT, ERR, "|$cmd|");

I find open($fh, "|$cmd");, and open($fh, "$cmd|"); easy to use, I just read/write from the filehandle. I just want one that works both ways.

Bonus points if one can also optionally read/write to a scalar instead.

I've been mucking around with open3 and IPC::Run but I can't seem to get them to work. Working example (perhaps with say grep) would be appreciated.

Edit: In response to comment, my current code:

open3($stdin_fh, $stdout_fh, $stderr_fh, $refresh_exec); #1
print "Opened"; #2
print $stdin_fh "Input to command\n"; #3

seems to hang before reaching line #2

and using IPC::Run:

start \@cmd_arr, $stdin_fh, $stdout_fh, $stderr_fh;
print "Opened"; #2
print $stdin_fh "Input to command\n"; #3

Runs the command but writes gives the error: Can't use an undefined value as a symbol reference.

I know my code is incomplete, but I don't want to paste 400 lines of code, and if I could successfully cut it down and isolate the problem I wouldn't need to ask the question.

I'm even unsure whether open3 or IPC::Run do what I want, so I'm just looking for a working solution I can build on.

Clinton
  • 22,361
  • 15
  • 67
  • 163

1 Answers1

0

I would:

  1. Redirect STD* to the desired FH's.
  2. Execute system($cmd);
  3. Restore STD* to their original state.

Have a look at Hari's example for detailed approach:

https://stackoverflow.com/a/1720592/1485996

You may also use local to avoid restoring STD.

Community
  • 1
  • 1
Mattan
  • 733
  • 7
  • 19
  • Can you show an example of how this allows me to `print` directly to `$cmd`s input like when using `open($fh, "|$cmd")`? – Clinton May 02 '13 at 14:41