O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required