perlfunctionexitdie

Perl run function on script exit/die


I have a question and could not find the answer i need. I have a perl script that works with several files. At the beginning of the script a given file is renamed and backed up, at the end of the script it is renamed back, so the original file is not touched at all. But what if the script dies while running, e.g. if a file is missing or if the user exits the script via "cmd + c" on the keyboard? Is there a method to define a function that is always executed when the script dies or the user wants the script to die? I found the "END"-block from perl, but it don't think that will work in my case.

Thank you!

-Alex


Solution

  • The END block works for exit and die. If doesn't work for signals, though, you'll have to create a signal handler. Setting it to an empty sub would pass the control to the END block:

    local $SIG{INT} = sub {};