Perl CookbookPerl CookbookSearch this book

3.10. Short Sleeps

3.10.1. Problem

You need to sleep for less than a second.

3.10.2. 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);

3.10.3. Discussion

Here's an example of select. It's a simpler version of the program in Recipe 1.6. 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;
}

3.10.4. See Also

The documentation for the CPAN modules Time::HiRes and Benchmark; the sleep and select functions in perlfunc(1) and Chapter 29 of Programming Perl; we use the select function for short sleeps in the slowcat program in Recipe 1.6



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.