BrowserUk has asked for the wisdom of the Perl Monks concerning the following question:

When I run the following one-liner and press the enter key (or ^M), I get no output for the first 3 presses, and 13 is output for the fourth (and subsequent) press. If I hit an alpha key, two of the 3 missing 13s are displayed before the ord of that alpha key.

perl -MTerm::ReadKey -E"ReadMode 3; say ord ReadKey( 0 ) while 1"

Can anyone a) confirm they see the same behaviour? b) explain it?

The ReadMode can be 3, 4, or 5 without affecting the results--but the latter two require ^Break to terminate the program.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
RIP an inspiration; A true Folk's Guy

Replies are listed 'Best First'.
Re: Term::ReadKey(0) and Windows
by kennethk (Abbot) on Sep 16, 2010 at 17:42 UTC
    Verified on ActiveState v5.8.9 built for MSWin32-x86-multi-thread with

    perl -MTerm::ReadKey -e "ReadMode 3; print ord ReadKey( 0 ) while 1"

    Also obtained expected (non-swallowing) behavior on v5.10.1 (*) built for x86_64-linux-gnu-thread-multi.

    No explanations come to mind. A quick read of Suffering from Buffering yielded no insight.

Re: Term::ReadKey(0) and Windows
by Marshall (Canon) on Sep 16, 2010 at 19:38 UTC
    Verified on Active State perl, v5.10.1 built for MSWin32-x86-multi-thread.

    I did notice one additional quirk: the sequence of alpha char, Enter, alpha char, Enter, alpha char, etc -> the enter isn't displayed until the following alpha character is pressed (and the 13 comes before that char). That sequence can evidently repeat forever. After a few tries like that Enter,Enter,Enter,Enter is required to get a single Enter to appear (first 3 vanished) as reported.

    Sorry I don't know why this happens, but this alternating behaviour might be an additional clue.

    Update: I think the answer elsewhere explained is a bug in Term::ReadKey and updating that module is clearly a great solution. I was hacking around with this prior to seeing that solution and found a way to make the desired output happen even with ActivePerl 5.10. I was surprised that ReadMode made a difference even when binmode was selected for stdin. Anyway there aren't any missing 013's in this code. Other readmodes will cause both the carriage return and line feed characters to appear and CTRL-C is a "3" instead of what it normally does and CTRL-break is required. Anyway...for whatever entertainment value it may have ...

    #!/usr/bin/perl -w use strict; use Term::ReadKey; ReadMode (3); #try mode 4 also! while (1) { binmode('stdin'); my $buf; read('stdin', $buf, 1, 0); print ord $buf; }
Re: Term::ReadKey(0) and Windows
by Anonymous Monk on Sep 16, 2010 at 20:57 UTC

      That fixed it for me too. Many thanks anonymonk.