tags:

views:

107

answers:

3

Hello, does the "or die $!"-part in the "close $fh or die $!;"-line any good?

#!/usr/bin/env perl
use warnings;
use strict;

my $file = 'my_file';
open my $fh, '<', $file or die $!;

print <$fh>;

close $fh or die $!;
A: 

Yes, the "or die" should do it.

However in practice checking for errors when closing a file is unnecessary, as the only error that close can ever reasonably give you was "bad file descriptor" i.e. the file wasn't open in the first place - which means it's effectively succeeded anyway.

You could also consider using Fatal. (perldoc Fatal)

MarkR
You could also get an error on close if the handle was opened to a pipe and the process terminated with an error.
hobbs
You can also get an error from a previous write (if the write was buffered and the error occurred after the system call had returned).
cjm
You can also get an error when the disk is full.
daxim
+7  A: 

If the file is open for reading that is not needed.

However, when file is open for writing it is possible that IO buffer could not be flushed at close, so it could be useful in that case

catwalk
+10  A: 

In your example, as it is at the end of your script and on a file open for reading, it is unncessary.

I'm trying to think if it's necessary when reading a pipe. Normally you close after an EOF condition, so I think it's not necessary either.

However, if you are writing, there are various errors that could be detected at close time. The most simple example is a full disk. This may not be reported until closing the filehandle because of buffering.

You can also use autodie (recommended above Fatal, I think).

FalseVinylShrub