in reply to Best way to timeout on a read

If you don't like goto, you can throw an exception instead:
use strict; use warnings; local $SIG{ALRM} = sub { die 'timeout' }; alarm(3); my $result = eval { <STDIN> }; alarm 0; if ( !defined($result) ) { print "Oh well, I didn't need that anyway...\n"; }

I don't know if that's the "best" way, but it certainly is better. (Maybe it's even better to do the local $SIG... in a smaller scope). And don't forget to reset alarm.

There are also various modules on cpan that do IO with timeouts and async IO.

Replies are listed 'Best First'.
Re^2: Best way to timeout on a read
by pjotrik (Friar) on Aug 20, 2008 at 18:46 UTC
    I second the recommendation to use exception instead of goto and to reset the alarm afterwards.

    Personally, I prefer to have the signal handler and alarm calls enclosed inside the eval as well - to me, it's more obvious what's going on that way. alarm and perlipc show the same approach:

    eval { local $SIG{ALRM} = sub { die "timeout" }; alarm 10; $input = <STDIN>; alarm 0; }; if ($@ and $@ =~ /timeout/) { print "Reading timed out"; } elsif ($@) { die "Other error: $@"; }