Re: How do I properly use global variables?
- From: pangj@xxxxxxxxxxxxx (Jeff Pang)
- Date: Tue, 23 Oct 2007 16:04:10 +0800
On 10/23/07, monk <rsarpi@xxxxxxxxx> wrote:
I'm having problems accessing a variable outside its subroutine.
I've tried several combinations too long to write here. Maybe I just
can't see the forest for the trees. But I'm lost. I need your
wisdom.
I'd like my program below to change $status to zero to exit the loop.
meaning...$> perl test.pl --start
it prints out indefinitely "hello world"
But if $> perl test.pl --stop
it gets out of the loop exiting the program.
Hi,
When script is running,how can you re-run it with another argument to
make it stop?
The general way to let a running program stop is to send a signal.
Let me modify your code to,
use strict;
use warnings;
our $status = 1;
$SIG{TERM} = $SIG{INT} = sub {$status = 0};
start();
sub start {
while ($status){
print "hello world!\n";
sleep 1;
}
print "out of loop. Will exit now\n";
exit 0;
}
__END__
When you run it,you can send SIGINT or SIGTERM to let it exit gracefully.
Given the process id is 1234,under unix you can say,
$ kill -s 2 1234
The script would print "out of loop. Will exit now" and exit.
(-s 2 means sending SIGINT,see `man 7 signal` for details).
The most important change for the code above is that we re-defined
singal handlers:
$SIG{TERM} = $SIG{INT} = sub {$status = 0};
When the script receive SIGTERM or SIGINT,it set the global $status to
0,so the loop condition become false,the program exit.
.
- Follow-Ups:
- Re: How do I properly use global variables?
- From: Matthew Whipple
- Re: How do I properly use global variables?
- References:
- How do I properly use global variables?
- From: Monk
- How do I properly use global variables?
- Prev by Date: Re: How do I properly use global variables?
- Next by Date: Re: Perl module
- Previous by thread: Re: How do I properly use global variables?
- Next by thread: Re: How do I properly use global variables?
- Index(es):
Relevant Pages
|
|