Why is the destructor object not called when the script exits?

I have a test script as follows:

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 is not called if the script exits with Ctrl-C. Is it also possible to call a destructor in this case?

+7
perl signals destroy
source share
2 answers

As Robert mentioned, you need a signal handler.
If you only need to call the object's destructor, you can use this:

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

+7
source share

You will need to configure 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 like that. Then in your main loop just mark $terminate , and if it sets the program to exit normally.

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

+6
source share

All Articles