in reply to Have $SIG{INT} ask if user wants to quit

The below one works for me

use strict; use warnings; $SIG{INT}=\&handler; sub handler { while(1) { print "Do you want to really quit....."; chomp(my $a=<STDIN>); if($a =~ /y/) { exit(0); } elsif($a =~ /n/) { return; } else { next; } } } while(1) { }

Is this you need???


--Lakshmanan G.

Your Attempt May Fail, But Never Fail To Make An Attempt

Replies are listed 'Best First'.
Re^2: Have $SIG{INT} ask if user wants to quit
by Anonymous Monk on Mar 11, 2009 at 08:02 UTC
    It's the oddest thing, but when I use this bit of code with a small and simple script, it works as expected. However, when I use it in my script with 6,500 lines of code, it works, but I have to hit enter three times after hitting "N" to resume the script (Y and every other key work as expected...). There must be something wrong in my code, but it's far too much to put in here. Anyway, would you agree that this is a more concise way of figuring out if user is entering Y or N, and are there other better ways of doing it??

    # define signal handler to catch contol-c $SIG{'INT'} = 'catch_int'; sub catch_int { my $ans; system("clear"); while ($ans !~ /[Nn]/) { print "Do you want to exit [y or n]? "; chomp($ans=<STDIN>); if ($ans =~ /[Yy]/) { exit(0); } } }

      You do quite a lot of work (calling some arbitary external program, writing to the current default handle, and reading STDIN) inside a signal handler. This will surely bite you with any old perl (before 5.7.3), and I won't bet that newer perls will have no problems. Don't put much work into signal handlers, just set a flag and handle it in the main loop -- or just exit() or die() immediately. See also Signals.

      Alexander

      -- Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)