I would like to clean the state of the script, close all filehandles etc, and I think the best way is to die(), but then, I would need external program to re-execute the script.

So I was thinking along the lines of:

system("perl -w script.pl"); die();

Howether, that would be problematic if there would be some resource that cannot be shared, and generally it would be better to have the script execute serially, and avoid the parallel execution of the same script.

To do that, I thought about something like that:

#!/usr/bin/perl sleep(10);
or even better:
#!/usr/bin/perl BEGIN { sleep(10); };

But it looks unclean and seems like it's not a very good solution.

How would correct solution look like?

update It seems that the correct solution is as suggested by tye:

exec( $^X, $0, @ARGV ) or die "Can't re-exec myself($^X,$0): $!\n";
it seems that besides loading new process image, it cleans up everything I can think of (fds, opened sockets)
Thanks.

UPDATE Howether, this doesn't work that well when you pack your scripts with PAR, then what you get is:

Unrecognized character \x7F at /home/eyck/script.exe Line 1

this is of course because script.exe is not a perl script, thus exec($0,@ARGV) should work in that case.


In reply to How to re-execute self? by Eyck

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.