| 1 |
#!/usr/bin/perl -w |
| 2 |
|
| 3 |
## Demonstration using a pipe to send input to a child process |
| 4 |
|
| 5 |
use strict; |
| 6 |
|
| 7 |
use IPC::Run qw( start pump finish ); |
| 8 |
|
| 9 |
die "usage: $0 <num>\n\nwhere <num> is a positive integer\n" unless @ARGV; |
| 10 |
my $i = shift; |
| 11 |
die "\$i must be > 0, not '$i'" unless $i =~ /^\d+$/ && $i > 0; |
| 12 |
|
| 13 |
my $out; |
| 14 |
|
| 15 |
my $h = start ['bc'], '<pipe', \*IN, '>', \$out; |
| 16 |
my $tmp = select IN; |
| 17 |
$| = 1; |
| 18 |
select $tmp; |
| 19 |
|
| 20 |
print IN "a = i = $i ; i\n"; |
| 21 |
|
| 22 |
while () { |
| 23 |
$out = ''; |
| 24 |
pump $h until $out =~ s/.*?(\d+)\n/$1/g; |
| 25 |
print "bc said: $out\n"; |
| 26 |
|
| 27 |
if ( $out > $i ) { |
| 28 |
## i! is always >i for i > 0 |
| 29 |
print "result = ", $out, "\n"; |
| 30 |
close(IN); |
| 31 |
last; |
| 32 |
} |
| 33 |
elsif ( $out == '1' ) { |
| 34 |
## End of calculation loop, get bc to output the result |
| 35 |
print IN "a\n"; |
| 36 |
} |
| 37 |
else { |
| 38 |
print IN "i = i - 1 ; a = a * i ; i\n"; |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
finish $h ; |