http://qs321.pair.com?node_id=643270

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

I'm trying to work out how to write well behaved __DIE__ and __WARN__ signal handlers. I've been looking at diagnostics and Devel::SummarizeWarnings, as well as perl's documentation (are there other useful examples?) It seems quite tricky to get right so I'm seeking Perl Wisdom on various aspects.

Firstly, I've seen this magic around:

$Carp::Internal{__PACKAGE__.""}++;
I think it's telling Carp that this package is part of Perl's warning system. There's some documentation in Carp.pm but I'm unclear in which circumstances it should be used (diagnostics uses it, so does Test::NoWarnings).

The $^S variable needs to be checked, the documentation warns of possible changes in __DIE__ handlers from eval { } if you don't.

Another issue is the interraction between handlers. Handlers generally try to play well with others, if there is already a custom __WARN__ or __DIE__ handler installed they are often written to call it (eg. diagnostics again).

Where should you stash the old handler? A lexical (diagnostics), a package var or in the installed closure (Devel::SummarizedWarnings). Another alternative for some circumstances would be making the caller decide. They can replace, local-ize or combine the handlers in either order. Yet another option is some kind of stack.

A related problem is knowing whether you've already install a handler. If handlers are being replaced the you can check the CODE address, but if the handlers are stacked or wrapped (which, as a module writer, you don't control) or if closures are being generated, then it gets more difficult. Is there some way to write a handler that can safely be indirectly wrapped around itself? If you call another handler should you temporarily put it back in %SIG so that it can recognize itself?

If handlers can be installed and later removed, is it work trying to detect misordered/unbalanced calls (ie. only uninstalling if we recognize the top handler).

I noticed it that the diagnostics handler uses goto &$oldwarn to keep the call stack clean for the wrapped handler. Is that good practice in general?

The handler stacking problem seems sufficiently messy that a conservative approach, "don't touch a custom handler", may be best.

There seems to be a risk of accidental recursion, at least I managed to do it. Are there techniques to play safe?

Are there any other tricks or traps?

Brad