On Tue, 12 Jun 2001, Avram Aelony <[EMAIL PROTECTED]> wrote,
> Hi,
>
> I commonly make use of statements like: print OUTFILE "Print
> results, data, or anything else\n";
> This is normally preceded by defining my file handle, as in something
> like: open(OUTFILE, ">newfile.txt");
>
> I'd like to know what *actually* happens internally if the filehandle,
> OUTFILE in this case, is not defined ahead of time?
> The output is shut off, but I would like to know if this is a good way
> to control output.
Ok, let's examine some examples.
#!/usr/bin/perl
# no -w, no warning
open FILE, ">/etc/passwd"; # no error checking
# should be permission denied for
# ordinary user, and disaster for
# for superuser
print FILE "sometext\n";
The output goes nothing.
perl -e 'print ACT_AS_FILEHANDLE "sometext\n";
No -w, prints nothing.
But watch this,
$ perl -we 'print ACT_AS_FILEHANDLE "sometext\n";
The -w switch tell Perl to warn you about what it thinks goes odd
(this is not the output of the code),
Name "main::ACT_AS_FILEHANDLE" used only once: possible typo at -e line 1.
Filehandle main::ACT_AS_FILEHANDLE never opened at -e line 1
$ perl -we 'open FILE, ">/etc/passwd"; print FILE "sometext\n";'
The same goes here,
print on closed filehandle main::FILE at -e line 1.
And when you a bit differently (not the "or die $!"),
$ perl -we 'open FILE, ">/etc/passwd" or die $!; print FILE "sometext\n";'
The code stops with message,
Permission denied at -e line 1.
This error message comes from $!. This is a control statement that works
like,
if (open FILE, ">/my/home/lets/use/another_file") {
print FILE "sometext\n";
} else {
die $!;
}
So when the open() doesn't work, you won't have the warning (even when
you put -w) since the print statement never executes.
The morals of the story:
* always use -w switch
* always check the return value of system call such as open()
>From the perldoc -f open,
"When opening a file, it's usually a bad idea to continue normal
execution if the request failed, so open() is frequently used in
connection with die()."
That's what you need to control the output.
hth
s::a::n
--
http://www.trabas.com