Debian Codegraph @

eg/factorial

raw
1 #!/usr/bin/perl -w
2
3 ## Demonstration of event-driven interaction with a subprocess
4
5 ## Event driven programming is a pain. This code is not that readable
6 ## and is not a good place to start, especially since few people (including
7 ## me) are familiar with bc's nuances.
8
9 use strict;
10
11 use IPC::Run qw( run );
12
13 die "usage: $0 <num>\n\nwhere <num> is a positive integer\n" unless @ARGV;
14 my $i = shift;
15 die "\$i must be > 0, not '$i'" unless $i =~ /^\d+$/ && $i > 0;
16
17 ## bc instructions to initialize two variables and print one out
18 my $stdin_queue = "a = i = $i ; i\n";
19
20 ## Note the FALSE on failure result (opposite of system()).
21 die $! unless run(
22 ['bc'],
23 sub {
24 ## Consume all input and return it. This is used instead of a plain
25 ## scalar because run() would close bc's stdin the first time the
26 ## scalar emptied.
27 my $r = $stdin_queue;
28 $stdin_queue = '';
29 return $r;
30 },
31 sub {
32 my $out = shift;
33 print "bc said: ", $out;
34
35 if ( $out =~ s/.*?(\d+)\n/$1/g ) {
36 ## Grab the number from bc. Assume all numbers are delivered in
37 ## single chunks and all numbers are significant.
38 if ( $out > $i ) {
39 ## i! is always >i for i > 0
40 print "result = ", $out, "\n";
41 $stdin_queue = undef;
42 }
43 elsif ( $out == '1' ) {
44 ## End of calculation loop, get bc to output the result.
45 $stdin_queue = "a\n";
46 }
47 else {
48 ## get bc to calculate the next iteration and print it out.
49 $stdin_queue = "i = i - 1 ; a = a * i ; i\n";
50 }
51 }
52 },
53 );