Event::Join - join multiple "events" into one
use Event::Join;
my $joiner = Event::Join->new(
on_completion => sub {
my $events = shift;
say 'Child exited with status '. $events->{child_done};
},
events => [qw/stdout_closed child_done/],
);
watch_fh $stdout, on_eof => sub { $joiner->send_event('stdout_closed') };
watch_child $pid, on_exit => sub { $joiner->send_event('child_done', $_[0]) };
start_main_loop;
When writing event-based programs, you often want to wait for a number of events
to occur, and then do something. This module allows you to do that without
blocking. It simply acts as a receiver for a number of events, and then calls
a callback when all events have occurred.
Note that although I mainly use this for "real" event-based
programming, the technique is rather versatile. A config file parser could be
implemented like this:
my $parsed_doc;
my $parser_state = Event::Join->new(
events => [qw/username password machine_name/],
on_completion => sub { $parsed_doc = shift },
);
while(!$parsed_doc && (my $line = <$fh>)){
chomp $line;
my ($k, $v) = split /:/, $line;
$parser_state->send_event($k, $v);
}
say 'Username is '. $parsed_doc->{username};
Create an instance. Needs to be passed "events", an arrayref of valid
event names, and "on_completion", a coderef to call after all events
have been received. This coderef is passed a hashref of events and their
values, and will only ever be called once (or not at all, if the events never
arrive).
Send an event. $event_name is required, and must be an event that was passed to
the constructor. An exception will be thrown if the name is not valid.
$event_value is optional; is is the value that goes into the hash to be passed
to the callback. It can be true or false -- its value does not affect whether
or not the completino callback is called.
Finally, an exception is thrown if an event is sent more than once.
Returns true if the event has been sent, false otherwise. Note that the true
value is
not the value that was passed to "send_event", it is
just an arbitrary non-false value.
Returns a coderef that sends $event_name when run. The first argument to the
coderef will become the second argument to "send_event".
Is the module totally broken? Patch my repository at:
http://github.com/jrockway/event-join
Jonathan Rockway "<jrockway@cpan.org>"
Copyright (c) 2009 Jonathan Rockway.
This module is Free Software. You may distribute it under the same terms as Perl
itself.