every(seconds => 4)

T

Ted Zlatanov

I've extended the every() function I discussed before to handle the
'seconds' syntax, so you can say

while (<>)
{
...
if (every(seconds=>60))
{
# do this every minute when input arrives
}
elsif (every(5000) || every(943, "second one")) # distinguish the second call's hash entry
{
}
}

Here's my implementation, which preserves the semantics of the original
every(N) function as well. I'm curious if anyone has ideas for more
things I can add. I am debating if it's worth putting on CPAN (I don't
know of anything like it already on CPAN). It seems like a really
simple piece of code that doesn't necessarily merit its own module, but
it's really useful to me...

Ted

{
my %counters;
my %time_counters;
sub every
{
my ($div, @id) = @_;

if ($div eq 'seconds')
{
$div = shift @id; # the number follows the 'seconds' string

$time_counters{caller(), $div, @id} ||= time;

my $then = $time_counters{caller(), $div, @id};
my $diff = time - ($then + $div);
return ($diff >= 0) ? ($time_counters{caller(), $div, @id} = time) : 0;
}
# else...
return !(++$counters{ caller(), $div, @id } % $div);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top