Here is an example using 'bc' the calculator. It uses IPC::Open3.
(There are pitfalls to watch out for with IPC, like when you try to get huge output thru the buffered pipes....but you will know it if you hit that problem :-) )
#!/usr/bin/perl
use warnings;
use strict;
use IPC::Open3;
use IO::Select;
#interface to "bc" calculator
my $pid = open3(\*WRITE, \*READ,\*ERROR,"bc");
#if \*ERROR is false, STDERR is sent to STDOUT
my $selread = new IO::Select();
my $selerror = new IO::Select();
$selread->add(\*READ);
$selerror->add(\*ERROR);
# may not be best use of IO::Select, but it works :-)
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";
#timing delay needed tp let bc output
select(undef,undef,undef,.01);
#see which filehandles have output
if($selread->can_read(0)){print "ready->read\n"}
if($selerror->can_read(0)){print "ready->error\n"}
#get any error from bc
sysread(ERROR,$error,4096) if $selerror->can_read(0);
if($error){print "\e[1;31m ERROR-> $error \e[0m \n"}
#get the answer from bc
sysread(READ,$answer,4096) if $selread->can_read(0);
if($answer){print "$query = $answer\n"}
($error,$answer)=('','');
}
waitpid($pid, 1);
# It is important to waitpid on your child process,
# otherwise zombies could be created.
I'm not really a human, but I play one on earth.
flash japh
|