On Wed, Aug 25, 2010 at 02:39, Kammen van, Marco, Springer SBM NL <marco.vankam...@springer.com> wrote: > ----Original Message----- > From: Chas. Owens [mailto:chas.ow...@gmail.com] > Sent: Friday, August 20, 2010 4:07 PM > To: Kammen van, Marco, Springer SBM NL > Cc: beginners@perl.org > Subject: Re: test contents of variable using alarm() > > On Fri, Aug 20, 2010 at 04:34, Kammen van, Marco, Springer SBM NL > <marco.vankam...@springer.com> wrote: >> Hi All, >> >> I want to use timers to check if certain variables are set and if not >> send some data back to a client... >> >> Been searching for this a while now, but all I can find on alarm are >> examples on timing out commands.... > snip > >>>All the [alarm][0] function does is send the [ALRM][0] signal to the >>>current process after X seconds. It is often used to turn a blocking >>>function into a non-blocking function (i.e. a timeout), but any code >>>can be put into the signal handler. Here is some code that does >>>something different with it: > > Hi Chas, > > I'm looking for something like this, I'm not sure if alarm() is made for such > checks but I'm wondering how to do this... > > > Timer for 30 seconds > If ($data eq "something") { > Print "OK\n"; > } else { > After 30 seconds > Print "No data received, try again later\n"; > } > > Marco! >
Given that pseudocode, the else clause will always be run. You have no code that modifies $data. Since you use the word received, I am going to assume that you are trying to read from a filehandle (which may be connected to a socket). If you just want to do nothing for thirty seconds (i.e. you don't need to interrupt a blocking function call), then you probably want the [sleep][0] function instead of the alarm function. #!/usr/bin/perl use strict; use warnings; use Try::Tiny; my $wait = 2; my $data; try { local $SIG{ALRM} = sub { die "timeout" }; alarm $wait; $data = <>; alarm 0; } catch { die $@ unless $@ eq "timeout"; }; if (defined $data) { print "OK\n"; } else { print "No data received, try again later\n"; } [0]: http://perldoc.perl.org/functions/sleep.html -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/