http://qs1969.pair.com?node_id=261000

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

Hi All,
In a nutshell my question is this: how do you get a signal handler to print the contents of a lexically scoped variable?

For those who need a code example please view the following as a summary of the problem

$SIG{INT} = sub { die "borked on $var"; }; alarm(1); while(1) { my $var = "wibble"; } alarm(0);

Now that is an extreeme example as sigint will be called everytime. But I think it makes my point.

When ran under use strict I get the following error message:
Global symbol "$var" requires explicit package name...

Other than putting this var into global scope is there anyway I can pass the var to the signal handler?

TIA

!unlike

I write my Perl code like how I like my sex: fast and dirty. ;)

Replies are listed 'Best First'.
Re: lexical variables and signal handlers
by fglock (Vicar) on May 27, 2003 at 14:47 UTC

    Use a global pointer:

    $SIG{INT} = sub { die "borked on $$ptr"; }; alarm(1); while(1) { my $var = "wibble"; $ptr = \$var; } alarm(0);

      Nice idea, cheers

      !unlike

      I write my Perl code like how I like my sex: fast and dirty. ;)

Re: lexical variables and signal handlers
by Lachesis (Friar) on May 27, 2003 at 14:52 UTC
    If you want to trigger from the alarm, you'll want to use $SIG{ALRM} rather than INT. You don't have to put $var global it just needs to be in the same scope as the signal handler so you could have
    alarm(1); while(1) { my $var = "wibble"; $SIG{ALRM} = sub { die "borked on $var"; }; } alarm(0);
    That said I assume that you want to a bit more than just trigger an alarm so it might help if you could give it bit more context
Re: lexical variables and signal handlers
by broquaint (Abbot) on May 27, 2003 at 14:50 UTC
    Other than putting this var into global scope is there anyway I can pass the var to the signal handler?
    Short of either declaring the lexical into a scope visible and above that of the signal handler or using a package variable there's nothing you can do using bare bones perl. However you can use PadWalker to access variables outside of your current scope, the only problem is that it might not play well with signal handlers.
    HTH

    _________
    broquaint

Re: lexical variables and signal handlers
by Elian (Parson) on May 27, 2003 at 15:47 UTC
    The answer, for perls before 5.8.0, is you don't and you shouldn't. The signal handler code you use is not interrupt safe, and will sometimes core perl if you use it. Things are better with 5.8.0, though if you build with unsafe signals you'll still have that problem.