Maybe something like the following? Each stage reads from its standard input and writes to an output pipe, which it sets up before starting processing. Each stage recursively sets up the following stage by opening the pipe to it. The last stage is a bit different, writes to STDOUT, so no need to open anything.
I haven't refactored the code, for better illustrating the fact that the stageX functions can (should?) be different.
The best way to develop a program in this way would be to develop the stageX functions as independent scripts (reading and writing to STDIN and STDOUT), then adapting them to this framework.
Try feeding it a large text file and see the results:
#!/usr/bin/perl -w use Getopt::Std; sub stage1 { my $out; open $out,"|$0 -m2" or die "Can't fork.\n"; while (<STDIN>) { chomp; printf $out "S1>%s\n",$_; } close $out; } sub stage2 { my $out; open $out,"|$0 -m3" or die "Can't fork.\n"; while (<STDIN>) { chomp; printf $out "S2>%s\n",$_; } close $out; } sub stage3 { my $out; open $out,"|$0 -m4" or die "Can't fork.\n"; while (<STDIN>) { chomp; printf $out "S3>%s\n",$_; } close $out; } sub stage4 { while (<STDIN>) { chomp; printf "S4>%s\n",$_; } } my %mode = ( 1 => \&stage1, 2 => \&stage2, 3 => \&stage3, 4 => \&stage4, ); getopt("m:"); if (defined($opt_m)) { if (exists($mode{$opt_m})) { $mode{$opt_m}(); } else { die "Mode '$opt_m' undefined.\n"; } } else { die "usage: $0 -m <mode>\n"; }
In reply to Re: IO:: ... dynamic?
by jorgegv
in thread IO:: ... dynamic?
by Tanktalus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |