The proper way to open()

James Laver james.laver at
Mon Jan 30 16:58:32 GMT 2012

On 30 Jan 2012, at 16:46, Roger Burton West wrote:

> What's a good way of opening a file as read-only, and failing if it
> doesn't exist? open() just returns a handle that's not obviously
> invalid, which strikes me as odd behaviour. At the moment I'm doing
> something like:
>  open IN,"<$cfg";
>  if (eof IN) {
>    die "bad config file $cfg\n";
>  }
> R

-r $file (readability test) is a good start, and checking the return value of open is a solution (just using -r would of course introduce a race condition). Autodie is also brilliant for avoiding having to write this:

open(...) or die(...)

as it will implicitly write the latter half of that for you. 

Two things:
- There is a 3 argument form of open   -- open(FH,'<',$file)  -- which is a good idea to use.
- Using a lexical filehandle as opposed to a bareword one makes everything shiny and nice


More information about the mailing list