every(seconds => 4)

Discussion in 'Perl Misc' started by Ted Zlatanov, Feb 29, 2008.

  1. Ted Zlatanov

    Ted Zlatanov Guest

    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);
    }
    }
    Ted Zlatanov, Feb 29, 2008
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. tshad
    Replies:
    7
    Views:
    16,907
    tshad
    Mar 11, 2005
  2. 00_CP_D12
    Replies:
    3
    Views:
    8,876
    dilipv
    Feb 22, 2008
  3. Stu
    Replies:
    7
    Views:
    1,727
    Dave Thompson
    Mar 7, 2005
  4. Michael Tan
    Replies:
    32
    Views:
    933
    Ara.T.Howard
    Jul 21, 2005
  5. `p
    Replies:
    7
    Views:
    352
    Steve Litt
    Dec 14, 2005
Loading...

Share This Page