Lucas Rey Lucas Rey - 2 months ago 13
Perl Question

Execute command every 1 second during loop in PERL

I have to execute command each second during a loop IN PERL. I'm trying the following sample code using epoch time, but it doesn't work because it prints continuosly:

#!/usr/bin/perl
my $checktime = time() + 1;
while(1) {
if ( $checktime => time() )
{
print "This should be print each second..." . "\n";
$checktime = time() + 1;
}
# DO SOMETHING ELSE
}


I cannot use sleep or freeze commands because during loop I have to execute other commands without interrupt the execution.
Could you please help me?

Thank you,
Lucas

Answer

Your if condition is bogus, => is not "greater or equal" operator, and comparing times are reversed,

my $actiontime = time();
while (1) {
    if ( time() >= $actiontime )
    {
       $actiontime += 1;
       print "This should print each second...\n";
    }
    # DO SOMETHING ELSE
}