LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   In perl is there a way when i call exit function to execute a subroutine (https://www.linuxquestions.org/questions/programming-9/in-perl-is-there-a-way-when-i-call-exit-function-to-execute-a-subroutine-558220/)

alix123 06-01-2007 03:16 AM

In perl is there a way when i call exit function to execute a subroutine
 
In perl is there a way when i call exit function to execute a subroutine.

The problem is i have a perl file + with custom perl modules and Iam exiting at some places in the custom perl modules when it finds some bad values. is there way when iam calling 'exit' to always call a another subroutine.

Take a look at the following ,basically I want to call onexit function in onexit.pm, whenever there is an exit from any of the modules or from the main file.

###a.pl

use module1.pm
use module2.pm

&module1::funct1()

&module2::funct2()


######################
#module1.pm

sub funct1() {

if($badvalues) {
exit;

}
}

#######################

#module2.pm

sub funct2() {

if($badvalues) {
exit;

}
}
#################################


###onexit.pm

sub onexit()
{
###do some jobs if there is a exit...from module 1 and module 2 and #a.pl.

}

druuna 06-01-2007 03:34 AM

Hi,

Although this is not what you ask, but it does fit your example: Why not call the 'onexit' subroutine and exit from there?

Taking your example, this would look like this:

Code:

######################
#module1.pm
sub funct1() {
  if($badvalues) {
    onexit;
  }
}

#######################
#module2.pm
sub funct2() {
  if($badvalues) {
    onexit;
  }
}
#################################
###onexit.pm
sub onexit()
{
  ###do some jobs if there is a exit...from module 1 and module 2 and #a.pl.
  exit
}

Hope this helps.

flupke 06-01-2007 03:34 AM

I don't see a way to do exactly what you want (I suppose some perl guru will give you a better answer than mine)
Meanwhile, maybe you could make it work in another way :

IF you have control on the modules, instead of exiting you send your own process a signal (would it be SIGUSR1 or SIGTERM or something else) and you trap this signal in your main file.

You can see how to catch signals at the very beginning of the man perlipc.


HTH
Flupke

bigearsbilly 06-01-2007 05:38 AM

simple, put this at the end of your main script...

Code:

END {
      print "Clean up\n"
      # clean up code here
};

you can put END in the modules as well, they will be executed in
reverse order of definition, so you must put main END before your use
clause as the use is parsed before anything else.


All times are GMT -5. The time now is 11:52 AM.