Wed, 08 Mar 2006

Perl open()

Dear perl programmers,

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

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

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.

[perl,wtf] | # Read Comments (9) |

Comments

Hear hear!

On a side note: can I ask the stupid question where PivoxyWindowOpen comes from? Google gives too many false positives.
Posted by Peter Van Eynde at Wed Mar 8 12:59:17 2006
Hear hear!

On a side note: can I ask the stupid question where PivoxyWindowOpen comes from? Google gives too many false positives.
Posted by Peter Van Eynde at Wed Mar 8 13:27:37 2006
You probably want to read http://mail.python.org/pipermail/python-list/2003-August/178599.html
Posted by JD at Wed Mar 8 13:54:53 2006
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..
Posted by Elvis Cehajic at Wed Mar 8 15:41:03 2006
Also, modern perl should

  open my $file, "filename" or die "Couldn't open filename: $!"

since "my $file" will limit the scope of the handle.
Posted by Mark A. Hershberger at Wed Mar 8 21:44:19 2006
Aren't we all using IO::File these days? :)
Posted by JD at Wed Mar 8 21:49:01 2006
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: $!"
Posted by Mark A. Hershberger at Wed Mar 8 21:59:09 2006
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.
Posted by Ulf Härnhammar at Thu Mar 9 14:18:58 2006
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.
Posted by JD at Thu Mar 9 14:35:15 2006

Name:


E-mail:


URL:


Comment:


Please enter "fudge" to prove you are a human