views:

123

answers:

2

I have a test script like this:

package Test;
sub new { bless {} }
sub DESTROY { print "in DESTROY\n" }

package main;
my $t = new Test;
sleep 10;

The destructor is called after sleep returns (and before the program terminates). But it's not called if the script is terminated with Ctrl-C. Is it possible to have the destructor called in this case also?

+3  A: 

You'll have to set up a signal handler.

package Test;
sub new { bless {} }
sub DESTROY { print "in DESTROY\n" }

package main;

my $terminate = 0;

$SIG{INT} = \&sigint;

sub sigint { $terminate = 1; }

my $t = new Test;

while (1) {
    last if $terminate;
    sleep 10;
}

Something along these lines. Then in your main loop just check $terminate and if it's set exit the program normally.

What happens is that the cntl-c interrupts the sleep, the signal handler is called setting $terminate, sleep returns immediately, it loops to the top, tests $terminate and exits gracefully.

Robert S. Barnes
+3  A: 

As Robert mentioned, you need a signal handler.
If all you need is the object destructor call, you can use this:

$SIG{INT} = sub { die "caught SIGINT\n" };.

eugene y