A
A
artem782017-01-19 23:18:27
Perl
artem78, 2017-01-19 23:18:27

How to pause a loop on a key in the console in Perl?

The point is this. There is a long loop in which some action is performed.

$x = 1;
while ($x<99999) {
  sleep(3); # Тут что-то делаем ...
  say $x++;
}

You need to check if the user pressed the Pause button, then pause the execution and output something like "Press any key to continue". And when the user pressed any button - continue the loop where you left off.
Probably it is necessary to dig aside Term::TermKey.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pcdesign, 2017-01-20
@pcdesign

#!usr/bin/perl-w
use strict;
use Term::ReadKey;
use feature 'say';

ReadMode 4;
say "Нажмите любую клавишу для паузы";
say "Нажмите ESC для выхода";
my $key;
$| = 1;
my $x = 1;

sub check_esc {
    my $key = shift; 
    if ( ord($key) == 27 ) { ReadMode 0; exit 0; }
    else                   { return 1; }
}
    
while ( $x < 99999 ) {
    sleep 3;
    $x++;
    say $x; 
    if ( defined( $key = ReadKey(-1) ) ) {
        &check_esc($key);
        say "Ура, Пауза! Нажмите любую клавишу для продолжения ...";
        while ( not defined( $key = ReadKey(-1) ) ) { }
        &check_esc($key);
    }

}
ReadMode 0;

Result of work:
Нажмите любую клавишу для паузы
Нажмите ESC для выхода
2
3
4
5
Ура, Пауза! Нажмите любую клавишу для продолжения ...
6
7
8

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question