http://www.perlmonks.org?node_id=122611

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

What is the scope of a variable called with my in a signal handler anonymous subroutine? Right now I have this code:
my $rip_done = 0; $SIG{CHLD} = sub { $rip_done = 1; while( waitpid(-1, WNOHANG) > 0) {} };
elsewhere in the program...
if($rip_done == 1) { do some stuff }
In the interest of having as few global variables as possible, can I initialize $rip_done inside the sub and still use it elsewhere in the program? I'm still trying to get away from using global variables for everything so I'm not 100% up to snuff on scope yet. I'm also new to signal handlers so if I'm not doing things right here, please let me know. Thanks a lot.

Replies are listed 'Best First'.
Re: Variable Scope in a Signal Handler?
by Fastolfe (Vicar) on Nov 01, 2001 at 22:02 UTC
    Yes, if you use a global variable or if your signal handler is a closure with a lexical in the scope you're after. Try this simple test and see if it prints out what you expect:
    { my $var = 1; $SIG{HUP} = sub { print "HUP; \$var=$var\n"; $var++; }; } print "in main program, \$var=$var\n"; kill('HUP', $$); print "in main program, \$var=$var\n"; kill('HUP', $$); print "in main program, \$var=$var\n";
    Then try moving $var into the main program and declare it with 'use vars'.