Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Variable Scope in a Signal Handler?

by Indomitus (Scribe)
on Nov 01, 2001 at 21:54 UTC ( [id://122611]=perlquestion: print w/replies, xml ) Need Help??

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'.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://122611]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (1)
As of 2024-09-10 05:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.