in reply to Process command output after each input
An IPC::Open2 example( put it in a loop if needed):
#!/usr/bin/perl #prompts for an string to evalute #(line 2+2, or 5x7, 5*6 / 3 , etc) #sends it to the bc calculator, #then reads the answer, and prints. use IPC::Open2; use strict; use warnings; my ($rd, $wr); open2($rd, $wr, "bc"); print "Enter a string to evaluate\n"; my $prompt= <STDIN>; print $wr "$prompt"; my $x = <$rd>; print $x; close($rd); close($wr);
A simple IPC::Open3 example
#!/usr/bin/perl use warnings; use strict; use IPC::Open3; #interface to "bc" calculator #my $pid = open3(\*WRITE, \*READ, \*ERROR,"bc"); my $pid = open3(\*WRITE, \*READ,0,"bc"); #if \*ERROR is false, STDERR is sent to STDOUT while(1){ print "Enter expression for bc, i.e. 2 + 2\n"; chomp(my $query = <STDIN>); #send query to bc print WRITE "$query\n"; select(undef,undef,undef,2); #get the answer from bc chomp(my $answer = <READ>); print "$query = $answer\n"; } waitpid($pid, 1); # It is important to waitpid on your child process, # otherwise zombies could be created.
A more complex IPC::Open3 example:
#!/usr/bin/perl use warnings; use strict; use IPC::Open3; use IO::Select; #interface to "bc" calculator my $pid = open3(\*WRITE, \*READ,\*ERROR,"bc"); my $sel = new IO::Select(); $sel->add(\*READ); $sel->add(\*ERROR); my($error,$answer)=('',''); while(1){ print "Enter expression for bc, i.e. 2 + 2\n"; chomp(my $query = <STDIN>); #send query to bc print WRITE "$query\n"; foreach my $h ($sel->can_read) { my $buf = ''; if ($h eq \*ERROR) { sysread(ERROR,$buf,4096); if($buf){print "ERROR-> $buf\n"} } else { sysread(READ,$buf,4096); if($buf){print "$query = $buf\n"} } } } waitpid($pid, 1); # It is important to waitpid on your child process, # otherwise zombies could be created.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Process command output after each input
by barryr (Initiate) on Dec 14, 2004 at 06:49 UTC | |
by zentara (Cardinal) on Dec 14, 2004 at 12:35 UTC | |
by Anonymous Monk on Jan 25, 2005 at 06:25 UTC | |
|
Re^2: Process command output after each input
by Anonymous Monk on Jan 25, 2005 at 06:47 UTC | |
by zentara (Cardinal) on Jan 25, 2005 at 12:29 UTC | |
by Anonymous Monk on Jan 25, 2005 at 18:11 UTC | |
by zentara (Cardinal) on Jan 25, 2005 at 18:26 UTC | |
by Anonymous Monk on Jan 25, 2005 at 19:13 UTC | |
|