Reputation: 1734
I am trying to code a perl script which would compile a C++ program and then execute it by passing in the required values. After the execution, I need whatever is printed on the cmd for comparison with a sample code.
Right now my code compiles the cpp code perfectly and correctly executes it, but completes without passing in the values. All I am doing right now is use system commands
system("cl E:\\checker\\Perl\\temp.cpp");
system("temp.exe");
system("10");
system("20");
system("30");
system("40");
system("50");
The C++ Code is something like this
cin >> a;
cin >> b;
cin >> c;
cin >> d;
cin >> e;
The code correctly compiles and exectues, but the following values (which are inputs to the C++ code which is using cin) doesn't seem to work
Please note I am using the Visual Studio compiler. Also can someone tell me how I can extract the information outputted by the C++ code into maybe a perl array for comparison.
Upvotes: 1
Views: 328
Reputation: 1364
You can use IPC::Open2
to establish bidirectional communication between your Perl script and the other program, e.g.
use IPC::Open2;
use autodie;
my ($chld_out, $chld_in);
my $pid = open2(
$chld_out,
$chld_in,
q(bc -lq)
);
$chld_in->print("1+1\n");
my $answer = <$chld_out>;
print $answer;
kill 'SIGINT', $pid; # I don't believe waitpid() works on Win32. Possibly with Cygwin.
Unfortunately, buffering can make this approach a lot harder than one would hope. You'll also have to manually wait and reap the child process. An alternative would be to use a module like IO::Pty
or Expect
to create a pseudo-tty environment to simulate user interaction (but I believe these two only work in a Cygwin environment on Windows). There's also IPC::Run
, a more fully-featured alternative to IPC::Open2/3
.
See also: perlipc
and perlfaq8
.
The correct syntax for system
is either
system('command', 'arg1', 'arg2', ... , 'argn');
Or all as a single string, which allows shell interpretation (which you may not want):
system('command arg1 arg2');
system
does not capture output. Instead, use the backticks operator:
my $command_output = `command args`;
or its generic form qx
. (If you assign to an array, the output will be split on $/
and pushed onto the array one line at a time).
There is also the pipe form of open (open my $pipeh, '-|', 'command', 'arg1', ..., 'argn') or die $!;
) and the readpipe
function.
Upvotes: 4