Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need "close FILEHANDLE" check for errors?

Tags:

perl

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 $!;
like image 355
sid_com Avatar asked Jan 15 '10 07:01

sid_com


People also ask

How do I close a file in Perl?

To close a file handle, and therefore disassociate the file handle from the corresponding file, you use the close function. This flushes the file handle's buffers and closes the system's file descriptor. If no FILEHANDLE is specified, then it closes the currently selected filehandle.

Which of the following function opens a file in read only mode?

Sysopen Function You can use O_CREAT to create a new file and O_WRONLY- to open file in write only mode and O_RDONLY - to open file in read only mode. The PERMS argument specifies the file permissions for the file specified, if it has to be created.

How do I open a file in Perl?

Perl open file function You use open() function to open files. The open() function has three arguments: Filehandle that associates with the file. Mode : you can open a file for reading, writing or appending.


2 Answers

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).

like image 168
FalseVinylShrub Avatar answered Oct 17 '22 05:10

FalseVinylShrub


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

like image 39
catwalk Avatar answered Oct 17 '22 05:10

catwalk