Wrap the creation of your condvars and AE::io objects in your while loop and use callbacks on the condvars instead of procedural code to do the sequential tasks, something like this:
#!/usr/bin/perl
use strict;
use warnings;
use AnyEvent;
while (1) {
my $cv = AE::cv;
my (@output, @input);
my $input_waiting = AE::cv;
my $output_waiting = AE::cv;
my $input_from_stdin = AE::io *STDIN, 0, sub {
my $input = <STDIN>; # read it
push(@input, $input);
$input_waiting->send;
};
# what to do when $input_waiting has sent
$input_waiting->cb( sub {
push(@output, 'done');
$output_waiting->send;
});
# what to do when $output_waiting has sent
$output_waiting->cb( sub {
print shift(@output) ."\n";
$cv->send;
});
# wait for the main condvar
$cv->recv;
}
the while block ensures that new condvars and AE::io objects get created on each iteration of the loop. I used the simpler
AE API, but that shouldn't affect the functioning of the code. You could probably get by without the
$cv condvar, but it may be helpful as this is part of a larger application. You should look at the begin and end methods of
AE::condvar which enables the use of single condvars as mergepoints for events, and
Object::Event for a lightweight event registration and emitting library.