Timers in Perl
Here’s the Perl translation of the Go code example for timers:
Our program demonstrates the use of timers in Perl. Timers allow us to execute code at some point in the future or repeatedly at some interval.
use strict;
use warnings;
use Time::HiRes qw(sleep);
# Timers represent a single event in the future. You
# tell the timer how long you want to wait, and it
# will execute a given code block after that time.
# This timer will wait 2 seconds.
my $timer1 = {
seconds => 2,
code => sub {
print "Timer 1 fired\n";
}
};
# We'll use sleep to simulate the timer firing
sleep($timer1->{seconds});
$timer1->{code}->();
# If you just wanted to wait, you could have used
# sleep directly. One reason a timer may be useful is
# that you can cancel the timer before it fires.
# Here's an example of that.
my $timer2 = {
seconds => 1,
code => sub {
print "Timer 2 fired\n";
}
};
my $timer2_thread = async {
sleep($timer2->{seconds});
$timer2->{code}->();
};
# Stop the timer
$timer2_thread->cancel();
print "Timer 2 stopped\n";
# Give the timer2 enough time to fire, if it ever
# was going to, to show it is in fact stopped.
sleep(2);
To run this program, save it as timers.pl
and execute it with:
$ perl timers.pl
Timer 1 fired
Timer 2 stopped
The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.
Note that Perl doesn’t have built-in timer objects like Go does. Instead, we’ve simulated timers using hash references and the Time::HiRes
module for high-resolution sleep. For the cancellable timer, we’ve used a simple threading model with the threads
module. This is a basic approximation of Go’s timer functionality in Perl.
In a real-world scenario, you might want to use a more robust event loop or timer library, such as AnyEvent
or POE
, for more complex timer operations in Perl.