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


in reply to fork, %SIG, END.

First off, these are from my experiences trying the same thing, they may not be the best answers, but they do work for me.

1. END block.

2. To make sure you still exit with the return value that got you into the END block, make sure to put local $?; at the beginning of your end block.

If you don't do this, the return value of the last thing you do in the end block will be the return value back to the caller of the script (which for me is Autosys and it was causing a script that should have been returning failure to return success because my last statement was a successful print to STDERR that my script was returning failure.

3. The way I accomplished this was in my parent to have a my $_PARENT_PID = $$; as a global variable. Then in the END block, you can check:

if( $$ == $_PARENT_PID ) { # parent } else { # child }

Like I said, not the best way, but it worked. Maybe someone else will have some better solutions.

best of luck...

Replies are listed 'Best First'.
Re^2: fork, %SIG, END.
by eff_i_g (Curate) on Aug 19, 2005 at 19:01 UTC
    etm1777:

    it is my understanding that the program does not exit within the END block, but after the END block has completed; the scope returns to a global (file) one, where $? is then returned, like so:
    END { local $?; # preserve previous return code # do anything } # now, outside of the END block, # $? refers to the global and the # program officially terminates # using this value.
      I agree with that code block and think we are speaking towards the same thing. I use the local $? in my END block to preserve the exit code also.

      I think I brought it up as an heads up because that bit me in the butt when I first started using the END block, I wasn't preserving the $? and therefore code inside the END block was causing it to be modified and the script not exiting with the value I wanted.