perlquestion
davies
<b>The problem:</b><br><br>
I want to run code until the user hits a key (I don’t care which key). In old fashioned BASIC it’s simple:
<code>
count! = 0
DO
datain$ = INKEY$
count! = count! + 1
LOOP UNTIL LEN(datain$) > 0
PRINT count!
</code>
Running this for about a second results in half a million iterations. But I can’t work out how to do the same thing in Perl.
<br><br><b>I have tried:</b><br><br>
One way:
<code>
use strict;
use warnings;
use diagnostics;
my $count = 0;
my $char;
until (sysread STDIN, $char, 1) {
$count++;
}
print $count;
</code>
Another way, based on Perl cookbook recipe 15.6:
<code>
use strict;
use warnings;
use diagnostics;
use Term::ReadKey;
my $count = 0;
my $char;
ReadMode('cbreak');
while ($char eq "") {
$char = ReadKey(0);
$count++;
}
print $count;
</code>
<b>What happens:</b><br><br>
Both respond in the same way. They sit until a key is pressed, and then return 1. I've only waited for up to five seconds, but even if I get multiple iterations by waiting longer, it's not nearly fast enough. I think what is happening is that the code is being optimised too far, but I would welcome clarification on this. I don’t actually need the counter in the finished code – I’m trying to initialise a series of pseudo-random number generators, but that code isn’t relevant to this particular part of the problem. The counter is just there to satisfy me that something is happening.
<br><br>
TIA and regards,
<br><br>
John Davies