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

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

I've got a snazzy little script on the go and I've run into a little problem.

First, the background. I'm using a module written by a coworker that can accept a reference to a subroutine as a parameter. The module then runs this subroutine on each string that it returns as output. The referenced subroutine I've written takes each string, separates the values and puts them into an XML file via a homegrown XML module.

My script watches the size of the XML file and how long it's been running, and kills the process after a certain amount of time/size. The problem is, sometimes it gets killed mid-XML file write. This makes the XML invalid, and effectively useless.

What I want to do is install a signal handler in the subroutine that will wait for a second or two to allow the write to complete before killing the process. The problem I'm having is figuring out how to do this. Usually I'd just do the following (ala: The Perl Cookbook):

sub wait_for_it { $SIG{INT} = \&wait_for_it; sleep(3); } sub writing { local $SIG{INT} = \&wait_for_it; #finish writing }
But the problem is that I can only pass in one subroutine. I thought about using an anonymous subroutine, but then realized that I don't know how can I get it to assign itself to the $SIG{INT} within itself.

Admittedly, I'm not all that strong with signals or references, so the solution might be obvious to those who've dabbled in this area before. Guidance is much appreciated.

-aijin