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

Hi there,

I've got a question concerning interruption of user input with CTRL-C. What I'm trying to do is this:
# Main part while (1) { &get_input } sub get_input { # Give prompt $reply = <STDIN>; if ( .."CTRL-C pressed".. ) { return 0; } else { # continue... } }


But if I use $SIG{'INT'} I can only assign a subroutine as handler, not a command like 'return' or 'last'. Now the only way it works is if the user presses CTRL-C, finishes his/her input and presses enter. What I would like to see is that the input is interrupted and the get_input subroutine 'aborts' or returns.

Is there a way to do this with normal <STDIN> input without having to use Term::ReadLine or some equivalent (which I'm not familiar with)?

Replies are listed 'Best First'.
Re: Keyboard Input Interrupt
by t0mas (Priest) on Dec 05, 2000 at 18:15 UTC
    This works for me:
    #!/usr/bin/perl -w use strict; use vars qw($ret $reply); # Signal handler $SIG{INT} = 'intSub'; while (1) { $ret=get_input(); print "\nget_input returned: $ret\n"; } sub get_input { # Give prompt print "Enter value: "; $reply=<STDIN>; return 0 unless $reply; chomp($reply); print "You typed: $reply\n"; return 1; } sub intSub { # Reset signal handler $SIG{INT} = 'intSub'; };
    I've only used this code on win2k, so I can't say that it will work on *nix boxes. You'll have to try that for yourself.

    /brother t0mas