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.
Open returns nonzero on success, the undefined value otherwise.
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.
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).
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.
$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(...)) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With