SPUG: proper checking of file status after read? (mod_perl Apache2)

Ben Reser ben at reser.org
Thu Sep 18 11:08:56 CDT 2003


On Wed, Sep 17, 2003 at 08:46:29PM -0700, Fred Morris wrote:
> This brings up a question about the code which is being executed, and if it
> is correct.
> 
> 
>     open( INFILE, '/path/spec') ... no errors, notice no mode == read
> 
>     while ($line = <INFILE>) {
> 
>       all ok...
>     }
> 
>     if ($!) ... <--- this is what sporadically fails!
> 
> 
> The point is to determine that the file was read ok. If not like this, then
> how? Is $! unsafe/indeterminate when a file has been successfully read?
> 
> I don't see this behavior on my stable server, which is running older stuff.
> 
> If anybody's got any insights to share....

Per perlvar: 
If used numerically, yields the current value of the C "errno"
variable, or in other words, if a system or library call fails,
it sets this variable.  This means that the value of $! is
meaningful only immediately after a failure:
if (open(FH, $filename)) {
    # Here $! is meaningless.
    ...
} else {
    # ONLY here is $! meaningful.
    ...
    # Already here $! might be meaningless.
}
# Since here we might have either success or failure,
# here $! is meaningless.

In the above meaningless stands for anything: zero, non-zero,
"undef".  A successful system or library call does not
set the variable to zero.

So yes, your code is wrong.  The better way to write this is:
open (INFILE, '/path/spec') or die "Couldn't open /path/spec: $!";
@lines = <INFILE> or die "Error reading /path/spec: $!";
...

-- 
Ben Reser <ben at reser.org>
http://ben.reser.org

"Conscience is the inner voice which warns us somebody may be looking."
- H.L. Mencken



More information about the spug-list mailing list