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

Checking for Waiting Input

Problem

You want to know whether keyboard input is waiting without actually reading it.

Solution

Use the CPAN module Term::ReadKey, and try to read a key in non-blocking mode by passing it an argument of -1:

use Term::ReadKey;

ReadMode ('cbreak');

if (defined ($char = ReadKey(-1)) ) {
    # input was waiting and it was $char
} else {
    # no input was waiting
}

ReadMode ('normal');                  # restore normal tty settings

Discussion

The -1 parameter to ReadKey indicates a non-blocking read of a character. If no character is available, ReadKey returns undef.

See Also

The documentation for the Term::ReadKey module from CPAN; Section 15.6

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