Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to interrupt loop with keyboard input? 2

Status
Not open for further replies.

twintriode

Technical User
Jan 6, 2005
21
AU
I am stuck trying to figure out how to exit a simple while loop with keyboard input.

For example If I have a few functions that are being looped through, ie:

while ($exit ne 1){
&function1;
&function2;
&function3;
}

The thing is I want the three functions to keep looping (monitoring the system), until I press a key on the keyboard. So for example, to be used in the following way, loop until 't' is pressed on the keyboard, then break loop and display current cpu temp with another function.

I have tried things like:

do {
&function1;
&function2;
&function3;
} until ($in1 = <STDIN>);



but no luck it always breaks the looping to wait for input...

Any ideas would be much appreciated!

Thanks
 
Are you running this on a *nix system? If so, take a look at signal handlers. In particular, the Interrupt signal (ctrl+c).
 
Check out the Term::ReadKey module. Example:
Code:
#!perl
use strict;
use warnings;
use Term::ReadKey;

my $key;
ReadMode 4;
do {
    &func1;
    &func2;
    &func3;
} until (defined($key = ReadKey(-1)));

print "Got key: $key\n";
ReadMode 0;
 
Here's a variation that checks for input after each function returns, instead of cycling through all 3 functions before checking:
Code:
#!perl
use strict;
use warnings;
use Term::ReadKey;

my $key;
[b]my @funcs = (\&func1, \&func2, \&func3);[/b]
ReadMode 4;
[b]LOOP: while (1) {
    for my $f (@funcs) {
        &$f;
        last LOOP if defined($key = ReadKey(-1));
    }
}[/b]

print "Got key: $key\n";
ReadMode 0;
HTH

 
Thanks for your replies rharsh and mikevh very helpful thanks.

I didnt have the Term::ReadKey module so I had to figure out how to install it, done now and the first script from you, mikevh, does exactly as I wanted...

Thanks very much
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top