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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.