every(seconds => 4)

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

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...


 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);

Site Timeline