Search code examples
perlexitsubroutine

In Perl is there a way to restart the program currently running from within itself?


I am running a program in Perl that at one point evaluates data in an if statement called from within a subroutine, e.g.

sub check_good {
    if (!good) {
         # exit this subroutine
         # restart program
    } 
    else {
         # keep going
    }
} # end sub

The problem I have is with exiting and restarting. I know that I can just use exit 0; to exit straight out, but obviously this is not correct if I want to go back to the beginning. I tried calling the subroutine which essentially starts the program, but of course once it has run it will go back to this point again. I thought about putting it in a while loop, but this would mean putting the whole file in the loop and it would be very impractical.

I don't actually know whether this is possible, so any input would be great.


Solution

  • If you have not changed @ARGV, or you keep a copy of it, you could possibly do something like exec($^X, $0, @ARGV).

    $^X and $0 (or $EXECUTABLE_NAME and $PROGRAM_NAME, see Brian's comment below) are the current perl interpreter and current perl script, respectively.