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

Hi Monks, I'm trying to create a *very* simple console application which continuously displays text in a main loop until a user presses a key. I thought this would be easy to do, but i'm struggling to find a solution. The problem with the code below is of course that it is single-threaded, so it blocks until the user presses a key. Do I need to to fork another process to do this or is there a simpler way to do this ? This seems overly complicated for such a simple task.

As always, thank you for your time.

my $StdIn = new Win32::Console( STD_INPUT_HANDLE ); $StdIn->Mode( ENABLE_PROCESSED_INPUT); my $console = new Win32::Console(); $console->Cls( $FG_WHITE | $BG_GREEN ); while (1) { my $x = rand(10); $console->WriteChar($x,10,12); $console->Display(); $console->Cursor(0,22); my $Data = $StdIn->InputChar(1) if (lc $Data eq "q") { exit; } }

Replies are listed 'Best First'.
Re: Exiting main loop in Win32::Console
by wrog (Friar) on May 17, 2015 at 19:18 UTC
    Have you tried using ->PeekInput or ->GetEvents ?

    (as you've noticed, you need something that does not block the way ->InputChar does.)

    And it's not that simple; you are, after all, asking it to do two things at the same time (print stuff and listen for keyboard input).

    (never mind that most likely what you really want is something that's event driven, i.e., listening for both keyboard input and events from whatever it is you're monitoring that's going to cause the printed text to change...)

      Ah, that's the stuff was looking for!... GetEvents works very nicely!

      you are true perl monk... thank you!

Re: Exiting main loop in Win32::Console
by BillKSmith (Monsignor) on May 18, 2015 at 11:31 UTC
    Beware! This type of program is prone to subtle bugs. I once had to work on a Pascal program which appeared to have solved this problem. (I do not remember how.) It worked fine as long as the operator pressed the key before midnight.
    Bill