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

I am running perl version 5.12.4 and for some reason, Guard and friends aren't working?

If I try this:

perl -MGuard -e '{scope_guard { warn }; sleep 3 }'

...and wait for 3 seconds, then I get a warning. But if I break the program (ctrl-C) - SIGINT, nothing happens. The guard is never run.

This behaviour is the same with Scope::Guard and End. Maybe something with a change of the behaviour of global destruction when perl exits? Any suggestions?

Replies are listed 'Best First'.
Re: Guard, Scope::Guard and End defunct in perl 5.12?
by moritz (Cardinal) on Feb 07, 2012 at 15:12 UTC

    I think you misunderstood what those modules do.

    What they do is run a closure if a scope is exited with exceptions or control flow. They don't try to execute it under any conditions (and they wouldn't be very successful in case of a SIGKILL or a power failure).

      So I'll have to set up a signal handler and do my cleanup in there. I thought I could do a catch-all by using one of the guard modules.
Re: Guard, Scope::Guard and End defunct in perl 5.12?
by Anonymous Monk on Feb 07, 2012 at 15:11 UTC

    Ctrl+C

    $ perl -MGuard -le " $SIG{INT}=sub{warn 2}; {scope_guard { warn 1 }; +sleep 3 } " 1 at -e line 1. $ perl -MGuard -le " $SIG{INT}=sub{warn 2}; {scope_guard { warn 1 }; +sleep 3 } " 2 at -e line 1. 1 at -e line 1. $ perl -MGuard -le " $SIG{INT}=sub{warn 2}; {scope_guard { warn 1 }; +sleep 3 } " 2 at -e line 1. 2 at -e line 1. 2 at -e line 1. 2 at -e line 1. 2 at -e line 1. 2 at -e line 1. 2 at -e line 1. 2 at -e line 1. 1 at -e line 1. $ perl -MGuard -le " $SIG{INT}=sub{warn 2;exit }; {scope_guard { warn + 1 }; sleep 3 } " 2 at -e line 1. 1 at -e line 1.
    The last one also causes a "fault" here on win32 5.14.1
      Yes - so by setting up a signal handler, I can trigger the guard. Thanks (also to Moritz).