in reply to POE::Wheel::ReadWrite: "low priority" events
Here's the long way, which doesn't assume you know the minimum length of input records. I've added copious comments to make this more tutorial-like.
use warnings; use strict; use POE qw(Wheel::ReadWrite); my $S2 = POE::Session->create( inline_states => { _start => sub { $_[HEAP]->{input_buffer} = [ ]; $_[HEAP]->{reader} = POE::Wheel::ReadWrite->new( 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, process_next_input => \&process_next_input, } ); POE::Kernel->run(); exit; sub handle_input { # Buffer the input rather than process it immediately. my $buffered_count = push @{ $_[HEAP]{input_buffer} }, $_[ARG0]; # If this is the first input record in the buffer, then begin # processing input. We don't need to begin every time, since the # rest of the code will continue to process input as long as there's # something in the buffer. # However, we do want to pause the reader's input, since otherwise # it might slurp an entire file or stream into the input buffer # while we're doing something else. # Note that we can't just pause_input() if we want to handle one # input record at a time. For efficiency, POE::Wheel::ReadWrite may # have read multiple input records at once. if ($buffered_count == 1) { $_[HEAP]{reader}->pause_input(); $poe_kernel->yield('process_next_input'); } } # 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 process_next_input { # Get the next job from the input buffer. my $next_input = shift @{ $_[HEAP]{input_buffer} }; # If there was no next input, then resume input so more jobs can be # acquired from STDIN. unless (defined $next_input) { $_[HEAP]->{reader}->resume_input(); return; } # Simulate multi-event asynchronous work. print "Next input: $next_input\n"; $_[KERNEL]->yield('step_one', $next_input); } sub do_step_one { print " step one: $_[ARG0]\n"; $_[KERNEL]->yield('step_two', $_[ARG0]); } sub do_step_two { print " step two: $_[ARG0]\n"; $_[KERNEL]->yield('process_next_input'); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: POE::Wheel::ReadWrite: "low priority" events
by vlad_s (Novice) on Jan 20, 2012 at 18:11 UTC | |
by rcaputo (Chaplain) on Jun 24, 2012 at 22:14 UTC | |
by jdporter (Paladin) on Jun 24, 2012 at 22:32 UTC |