#!/usr/bin/perl -w

## Demonstration of using a scalar to queue input to a child process

use strict ;

use IPC::Run qw( run ) ;

die "usage: $0 <num>\n\nwhere <num> is a positive integer\n" unless @ARGV ;
my $i = shift ;
die "\$i must be > 0, not '$i'" unless $i =~ /^\d+$/ && $i > 0 ;

my $stdin_queue = "a = i = $i ; i\n" ;

## Note the FALSE on failure result (opposite of system()).
die $! unless run(
   ['bc'],
   sub { my $r = $stdin_queue ; $stdin_queue = '' ; $r },
   sub {
      my $out = shift ;
      print "bc said: ", $out ;
      if ( $out =~ s/.*?(\d+)\n/$1/g ) {
         if ( $out > $i ) {
	    ## i! is always >i for i > 0
	    print "result = ", $out, "\n" ;
	    $stdin_queue = undef ;
	 }
         elsif ( $out == '1' ) {
	    ## End of calculation loop, get bc to output the result
	    $stdin_queue = "a\n" ;
	 }
	 else {
	    $stdin_queue = "i = i - 1 ; a = a * i ; i\n" ;
	 }
      }
   },
) ;
