jb_using_perl has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I am trying to use "alarm" as a timeout mechanism inside a foreach loop. I am using the $SIG{ALRM} signal to execute a sub command that includes a "next" statement. Unfortunately, the sub command has trouble with the "next".

Here is my example:
#!/usr/bin/perl use strict; use warnings; my @time=(4,12,16,8); LABELME: foreach my $t (@time) { $SIG{ALRM} = sub {print "timeout\n"; next LABELME}; print "Start $t\n"; alarm(10); sleep($t); alarm(0); print "done with $t\n"; } print "All Done!\n";
And this is what prints:
Start 4 done with 4 Start 12 timeout Exiting subroutine via next at postalarm.pl line 8. Exiting eval via next at postalarm.pl line 8. Label not found for "next LABELME" at postalarm.pl line 8.
Thank you in advance for your help!
-jb_using_perl

Replies are listed 'Best First'.
Re: using "alarm" with SIGALRM
by Anonymous Monk on Jul 27, 2009 at 17:51 UTC
    adopted from perldoc -f alarm
    #!/usr/bin/perl use strict; use warnings; my @time=(4,12,16,8); LABELME: foreach my $t (@time) { eval { local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required print "Start $t\n"; alarm(10); sleep($t); alarm(0); print "done with $t\n"; }; if ($@) { die unless $@ eq "alarm\n"; # propagate unexpected errors print "timeout\n"; next LABELME; } else { # didn't } } print "All Done!\n";
      Thank you! That worked perfectly.
      -jb_using_perl