Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I was recently thinking about using tmpnam to generate a temporary file name for the duration of my process. I was happy to discover a complete solution in the Perl Cookbook, 7.5, "Creating Temporary Files",
do { $fn = tmpnam() } until open ... END { unlink($fn) or die "Couldn't unlink $name : $!" }
I have two questions about this code:
First, it seems that $fn must be a global variable so that the END block knows what to delete. Is this correct? (Or is there a way to set up the END-block as a closure?) Second, what is the point of putting a die statement in an END block?

Replies are listed 'Best First'.
Re: Tmpnam and END blocks
by Corion (Patriarch) on Jul 05, 2007 at 14:45 UTC

    An END { ... } block can be put into a closure as well:

    { my $fn; do { $fn = tmpnam() } until open ...; END { unlink $fn or warn "Couldn't remove '$fn': $!"; }; };

    The die is especially useless indeed - just warning is far saner, as the program is terminating anyway and other cleanup likely doesn't rely on the removal of a temporary file ...

Re: Tmpnam and END blocks
by archfool (Monk) on Jul 05, 2007 at 14:51 UTC
    I think the die's purpose is threefold:
    1) Just in case you need to do more processing after the unlink in the END block.
    2) So that any caller of the script knows that the script exited with errors (i.e. not retcode 0).
    3) So that the user is notified so maybe he/she can delete the file manually or find out why it couldn't unlink.
      1) Just in case you need to do more processing after the unlink in the END block.
      That makes sense, but I tend to think that the END{} block should do things as few as possible.
      2) So that any caller of the script knows that the script exited with errors (i.e. not retcode 0).
      It depends on the programmer whether the failure on unlink is considered an error or not. Unlinking temporary files (specially if originally created by the same process) shouldn't be that serious error. If the same process can't delete them, then it's not the issue of the program. It merely tells that something wrong might happen and it's out of its control to fix it. So, a warning message is sufficient in this case, and the exit code remains 0.
      So that the user is notified so maybe he/she can delete the file manually or find out why it couldn't unlink.
      The user will get notified with a warning message, and if this is a CGI program, the message goes to the web server error log as well. As to the "why", the reason can be given via $!.

      Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!