Simple Perl module for tracking time limits or deadlines.
use Time::Left qw(time_left);
# Progress indicator with time limit.
local $! = 1;
print "Working ...";
my $timer = time_left("10s");
until (done() or $timer->expired) {
Time::HiRes::sleep(0.25);
print ".";
}
die " timed out.\n"
unless done();
print " done.\n";
- Duration parsing - Accepts strings like "5m", "2h", "30s"
- Monotonic timing - Uses CLOCK_MONOTONIC when available to avoid clock skew issues
- Select-compatible - Returns undef for indefinite timers, perfect for select() timeouts
- Overloading - Boolean and string contexts work intuitively
- Simple API - Just 6 methods covering all use cases
cpanm Time::Left
use Time::Left qw(time_left to_seconds);
# From duration strings
my $timer = time_left("1m"); # 60 seconds
my $timer = time_left("2.5h"); # 2.5 hours
# From seconds
my $timer = Time::Left->new(60); # 60 seconds
# Indefinite (no timeout)
my $timer = time_left(undef);
my $sec = $timer->remaining; # Seconds left (or undef if indefinite)
my $active = $timer->active; # True if time remains
my $expired = $timer->expired; # True if time is up
# Boolean context uses active/expired
while ($timer) {
# Still time left
}
if (!$timer) {
# Timer expired
}
Time-limited socket read:
if (IO::Select->new($socket)->can_read($timer->remaining)) {
$socket->recv($buffer, 1024);
# Process data...
}
Conditional timeout setup:
# Set up alarm if timer is limited
Time::HiRes::alarm($timer->remaining)
if $timer->is_limited;
$s = to_seconds($duration)
- Convert duration string to seconds$t = time_left($duration)
- Create a Time::Left object
$t = $class->new($seconds)
- Constructor (seconds/undef only, no parsing)$s = $t->remaining
- Get seconds remaining (undef if indefinite)$bool = $t->active
- Check if timer has time left$bool = $t->expired
- Check if timer has run out$bool = $t->is_limited
- Check if timer has a limit (not indefinite)$t->abort
- Expire the timer immediately
- Perl 5.10+
- Time::HiRes
- Scalar::Util
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Brett Watson
- Time::HiRes - High resolution time functions
- IO::Select - OO interface to the "select" system call