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

Dear Monks,I have the following code. I want to handle Ctrl-C when waiting for $choice

# Handle Ctrl-C $SIG{INT} = \&ctrlc; use autodie; use Modern::Perl; use Storable qw {store retrieve}; my $dbfile = 'sbs.db'; my %person = %{ retrieve($dbfile) }; while() { print "\n(C)reate,(L)ist,(N)ew,(M)odify,(R)emove,(Q)uit? "; chomp(my $choice = <>); $choice = lc $choice; # # Some code here # } exit; sub ctrlc { store \%person,$dbfile; print "You used Ctrl-C!"; exit 1; }

When I press Ctrl-C, I get the following messages :

(C)reate,(L)ist,(N)ew,(M)odify,(R)emove,(Q)uit? Use of uninitialized v +alue $choice in chomp at J:\ps \monks.pl line 13. Use of uninitialized value $choice in lc at J:\ps\monks.pl line 14. You used Ctrl-C!

How can I avoid the error messages? And have a clean exit?

Replies are listed 'Best First'.
Re: Handle Ctrl-C on Windows
by marto (Cardinal) on Aug 28, 2012 at 10:32 UTC
Re: Handle Ctrl-C on Windows
by jethro (Monsignor) on Aug 28, 2012 at 09:49 UTC

    I don't get that warning on linux, so can't test, but the problem seems to be that the chomp is executed even after you pressed ctrl-C. Did you try to move the chomp on a line by itself or add a noop inbetween so that there is another statement to break on?

    my $choice = <>; chomp($choice); #or even my $choice = <>; $choice=$choice; chomp($choice);

      Thanks for your advice.Tried both, but the same results :(

Re: Handle Ctrl-C on Windows
by philiprbrenan (Monk) on Aug 28, 2012 at 11:49 UTC

    May I suggest that you call Storable::store() in your:

    # some code here

    processing on a regular basis? The problem with calling store() at random points is that the data structure you want to save may be in an inconsistent state. Storable::store is very efficient and so it is not a problem to call it frequently whenever you have made a consistent set of modifications to your data, perhaps, for example, at the end of your while loop. This would eliminate the need to catch the Ctrl-C in your code and so make your script simpler and more reliable.

      I have decided to do just that. I thank you for the reply.