Can I use POSIX signals in my Perl program to create event-driven programming?
If you want to do event-driven programming, take a look at one of the CPAN event modules, such as POE, Coro, or AnyEvent before you invent your own thing.
Update for 2020
I'm doing this with Mojo::EventEmitter, which I cover very briefly in my book Mojo Web Clients.
You can use select to monitor communications channels (note: if you are on Win32 select can only be used on a socket).
So you can use code like this:
use IO::Select;use IO::Handle;...$_->blocking(0) for @handles;while( 1 ) { my $s = IO::Select->new( @handles ); for my $h ( $s->can_read( 1 ) ) { my $data = read_handle($h); process_handle_data( $data ); }}sub read_handle { my $h = shift; my $got = ''; 1 while read( $h, $got, 1024, length $got ); return $got;}
Take a look at the UDP example in perlipc. It uses the select built-in. I prefer the core IO::Select
module to the select
built-in, it's much easier to read.
Update: You really should consider using an event framework like POE, Event or Coro. There's a pretty good list of options in this perlmonks thread. Don't fear CPAN.