in reply to Re: Any one know how to use sigtrap with moose?
in thread Any one know how to use sigtrap with moose?

Hi, Thanks for the reply, I would like to put all the signal handling code in Mypackage.pm. Not sure if it's possible. If I run
$ perl test_mypackage.pl
then run
$ ps -ef |grep perl |grep -v grep |awk '{print $2}' |xargs kill
Then end{} should print it's status.

Replies are listed 'Best First'.
Re^3: Any one know how to use sigtrap with moose?
by Corion (Patriarch) on Jul 24, 2012 at 11:35 UTC

    If you want some code to run at the end of your program, consider using an END block or an object destructor instead of using signal handlers. See perlsyn and/or perlobj.

Re^3: Any one know how to use sigtrap with moose?
by tobyink (Canon) on Jul 24, 2012 at 11:35 UTC

    You could try something along the lines of:

    use MyPackage; my $newest_instance; after BUILD => sub { $newest_instance = shift; };

    And then in your signal handler, call:

    if ($newest_instance) { $newest_instance->status("killed"); $newest_instance->end; }

    Note that if there is more than one object of class MyPackage knocking around, this will only set the status on the newest (i.e. most recently constructed) object.

    Depending on exactly what you're doing, and how many instances of MyPackage you expect to exist in the lifetime of a process, you may need something else.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      This approach will also keep $newest_instance around until the end of the program, which may or may not be what the OP intended.

        Indeed, but there's always Scalar::Util::weaken for that.

        perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
      Very smart! That's exactly what I'm looking for! Thanks! But the "after BUILD" part does not work, it complains about

      The method 'BUILD' was not found in the inheritance hierarchy for Mypackage at /usr/lib/perl5/Class/MOP/Class.pm line 1053

      So I changed to :
      sub BUILD{ $newest_instance = shift; }
      Then it works. may be I miss some perl modules...