in reply to Catching errors in closing lexical filehandles

The advantage of using lexicals is that you can use the same function to open multiple files at the same time without overwriting the handle. However, the handle must be kept in scope between open and close, so the function has to assign the handle value to something:
$ptr = &lock_file($path); # load $path with a regular open and do whatever operations on data... &unlock_file($ptr); sub lock_file { # Locks file by creating filepath.lock and flocking it. # Usage: $ptr = &lock_file($path); my $handle; my $path = (shift) . '.lock'; open($handle, ">$path"); flock($handle, 2); return [$handle, $path]; } sub unlock_file { # Unlocks file locked with &lock_file. # Usage: &unlock_file($ptr); my $inp = shift; my ($handle, $path) = @$inp; flock($handle, 8); close($handle); unlink($path); }
Using these functions, I can have multiple files locked simultaneously (on a system supporting flock), but I have to keep the handles stored between &lock_file and &unlock_file.

EDIT: To answer your question, you do your error checking on open, not close. Close will never have errors unless you drop the handle value from scope. I like to do:

if (!open($handle, $path)) { &error('myerror'); }

Having your code die isn't as good, because if you decide you want to output an error page instead of having the program quit, you have to go back in and change your code in many different places. Better to have an error sub.

Replies are listed 'Best First'.
Re^2: Catching errors in closing lexical filehandles
by gaal (Parson) on Sep 27, 2004 at 07:27 UTC
    Allowing multiple opens form the same code is a great benefit, perhaps even the greatest, but who said it's the only one? davido mentions a few others, all of which IMHO are valid.

    Regarding "you do your error checking on open, not close", this is not quite correct. Close can have errors, e.g. when the file is a pipe that has been closed on the other side.

    And regarding die, in the first instance, I was using it as a token for "any appropriate error handling I might choose to apply here". In the second instance, you can (and I often do) achieve protection from termination by catching the die with an eval somewhere up the call train.

      Yes, but the point of closing a file is to have it closed, and does it really matter whether it closes from the server side or the client side? Perhaps I should have said no important errors rather than no errors...
        This situation can be indicative of a real applicative failure. perlipc gives the matter some discussion in the secion called "Using open() for IPC".