Short Sleeps

Problem

You need to sleep for less than a second.

Solution

Use the select() function, if your system supports it:

select(undef, undef, undef, $time_to_sleep);

Some systems don’t support a four-argument select. The Time::HiRes module provides a sleep function that takes a floating point number of seconds:

use Time::HiRes qw(sleep);
sleep($time_to_sleep);

Discussion

Here’s an example of select. It’s a simpler version of the program in Section 1.5. Think of it as your very own 300-baud terminal.

while (<>) {
    select(undef, undef, undef, 0.25);
    print;
}

Using Time::HiRes, we’d write it as:

use Time::HiRes qw(sleep);
while (<>) {
    sleep(0.25);
    print;
}

See Also

The documentation for the CPAN modules Time::HiRes and BenchMark; the sleep and select functions in perlfunc(1) and Chapter 3 of Programming Perl; we use the select function for short sleeps in the slowcat program in Section 1.5

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.