Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check the success of open (file) in Perl?

Tags:

file-io

perl

The following (not very Perl-ish) code

#!/usr/bin/perl

if (! -e "mydir/")
{
  print "directory doesn't exist.\n";
}
open (my $fh, ">", "mydir/file.txt");
if ($fh)
{
  print "file opened.\n";
  print $fh;
  print $fh "some text\n" or die "failed to write to file.\n";
  close ($fh);
}
else
{
  print "failed to open file.\n";
}

produces the output such as this

directory doesn't exist.
file opened.
failed to write to file.
GLOB(0x...some-hex-digits...)

Why is $fh not equivalent to false following the open call? As mydir/ does not exist, I'd expect the attempt to open the file to fail.

I get similar results if the directory and file exist, but the file is read-only.

I've tried this with Perl 5.10.1 on Windows 7 x64, and with Perl 5.10.0 on Fedora-11 Linux.

I'm guessing my file handle test is wrong. I've tried Googling this without luck. I expect it's something obvious, but any hints or links would be much appreciated.

Thanks, Rob.

like image 912
Rhubbarb Avatar asked Jul 08 '10 13:07

Rhubbarb


People also ask

What does the Open return on success?

Open returns nonzero on success, the undefined value otherwise.

How do I know if a file is open in Perl?

It's possible to have a filehandle that's open to something other than a filedescriptor, in which case fileno sensibly returns undef. Examples are tied handles and handles opened to scalars. tell(FH) produces a warning with a closed filehandle. Using fileno() does not.

What is open function in Perl?

Description. This function opens a file using the specified file handle. The file handle may be an expression, the resulting value is used as the handle. If no filename is specified a variable with the same name as the file handle used (this should be a scalar variable with a string value referring to the file name).

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.


1 Answers

$fh isn't being set to a zero-ish value, it is being set to a GLOB as your code shows. This is different from what open returns which is why the idiom is

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

or

unless(open(...)) {
    ...
}
like image 63
msw Avatar answered Oct 11 '22 17:10

msw