Here's the shorter, less efficient method, which assumes you do know the minimum length of input records. It tunes the sysread() length down to the minimum record length to guarantee no more than one input record is read at a time.
Of course you could be ultra-conservative and tune sysread() down to one octet at a time. This would work in all cases, but the general rule is that You're Doing It Wrong™ if you ask Perl to process strings one octet at a time.
This example assumes lines of input are at least 10 octets each. It will fail on shorter input.
use warnings;
use strict;
use POE qw(Wheel::ReadWrite Driver::SysRW);
use constant MIN_RECORD_LENGTH => 10;
my $S2 = POE::Session->create(
inline_states => {
_start => sub {
$_[HEAP]->{input_buffer} = [ ];
$_[HEAP]->{reader} = POE::Wheel::ReadWrite->new(
# Reduce the sysread size to the minimum record length. This
# is less efficient than slurping larger chunks of input, but
# it prevents more than one record from being read at a time.
Driver => POE::Driver::SysRW->new(
BlockSize => MIN_RECORD_LENGTH,
),
Handle => \*STDIN,
InputEvent => 'got_input',
ErrorEvent => 'got_input_error',
);
},
got_input => \&handle_input,
got_input_error => \&handle_input_error,
step_one => \&do_step_one,
step_two => \&do_step_two,
}
);
POE::Kernel->run();
exit;
sub handle_input {
# POE::Wheel::ReadWrite's input buffer doesn't contain any more
# complete input records, so we can simply pause input here.
$_[HEAP]{reader}->pause_input();
# And begin processing the input secure in the knowledge that more
# records won't arrive until we're done.
print "Next input: $_[ARG0]\n";
$_[KERNEL]->yield('step_one', $_[ARG0]);
}
# Stop the reader on input error, which may simply be EOF.
# The program exits shortly afterwards.
# It may be useful to print the error later on.
sub handle_input_error {
delete $_[HEAP]{reader};
}
sub do_step_one {
print " step one: $_[ARG0]\n";
$_[KERNEL]->yield('step_two', $_[ARG0]);
}
sub do_step_two {
print " step two: $_[ARG0]\n";
# Resume input after we're done.
$_[HEAP]{reader}->resume_input();
}