I got the request to make a Perl script with the requirements as follow:
Make a program that just shows the time, a clock on the format 12:01:24.
When someone press key combination Ctrl -p the program should pause, ie the clock will stand still. When the Ctrl - p is pressed the second time the clock will start again.
I am a newbie in Perl & programming, so it's kind of a big job for me. Highly appreciate your support/advice.
Below is what I've tried. However, I use ^C to interrupt (don't know how to use ^P) and a select menu to resume couting time.
#!/usr/bin/perl
# The script is to couting time (show clock) and support Ctrl-C to pause clock
# then choose a key to continue couting or exit.
use strict 'vars';
$SIG{'INT'} = 'Pause'; # use signal handling, if press ^C, will interrupt and call sub Pause.
print "Press Ctrl-C to pause couting time \n";
our ($hour,$min,$sec) = ();
($hour,$min,$sec) = clock (0,0,0); # start couting with at 00:00:00
sub Pause {
print "\nCaught ^C\n";
print "Press \"c\" to continue, \"e\" to exit: ";
while (1) {
my $input = lc(getc());
chomp ($input);
if ($input eq 'c') {
clock($hour,$min,$sec);
}
elsif ($input eq 'e') {
exit 1;
}
}
}
# sub clock is to count time
sub clock {
our ($hour, $min, $sec) = @_; # declare as the global variables
while (1) {
sleep 1; # get clock of system for each one second
$sec++;
if ($sec == 60) {
$sec = 0;
$min++;
if ($min == 60) {
$min = 0;
$hour++;
$hour = 0 if ($hour == 24)
}
}
printf ("%2d:%2d:%2d\n",$hour,$min,$sec);
}
return ($hour,$min,$sec);
}
The output looks like:
C:\Program Files\Perl\mine>pause_func.pl
Press Ctrl-C to pause couting time
0: 0: 1
0: 0: 2
0: 0: 3
Caught ^C
Press "c" to continue, "e" to exit: c
0: 0: 4
0: 0: 5
Caught ^C
Press "c" to continue, "e" to exit: e
C:\Program Files\Perl\mine>
If you know how to have ^P to interrupt counting and other method to get this done, that would be great.