http://www.perlmonks.org?node_id=394090


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.