Perl open()

Dear perl programmers,

When using open(), please don’t use:

open FILE, "$file" or die "couldn't open filen";

It really helps if you tell us what file you’re trying to open and
what went wrong. The correct error message is:

open FILE, "$file" or die "could not open $file: $!n";

Thank you.

9 thoughts on “Perl open()

  1. That should be addressed to all programmers, not just the perl hackers. We had a lot of trouble with these kind of error messages when we first had to install a software which acquires data from a lab machine. The installation was on a networked pc running windows and should of course only run with user rights. The only error message we got when we started the program as a user was that it couldn’t access some file (not giving the path nor the file name of the file). This kind of problem is much harder to trace down in a windows environment with compiled software than using Linux and perl scripts..

  2. Why would I “use IO::File” when I can just “open”?

    Besides, this is the EXACTLY the same as

      my $file = IO::File->open(“filename”) or die “Couldn’t open filename: $!”

  3. Ulf Härnhammar
    on said:

    Surely you mean:

    open FILE, “<$file” or die “couldn’t open file: $!n”;

    Otherwise it could be a security vulnerability, if $file is controlled by a remote user and starts with a “|” character.

  4. Not really. That wasn’t part of the point I was trying to make. I intentionally left out the open action because my comments relate to all uses of open. In particular you failed to put the filename in the error message.

    Also, tainting should protect you against using user data in an open command.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.