Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

read closed directory handle?

by mkmcconn (Chaplain)
on Jan 27, 2001 at 02:35 UTC ( [id://54657]=perlquestion: print w/replies, xml ) Need Help??

mkmcconn has asked for the wisdom of the Perl Monks concerning the following question:

Why does this work?
#!/usr/bin/perl -w use strict; opendir (TOPDIR,"$ENV{HOME}") or die "Thus shall ye likewise perish: $!"; close TOPDIR; while ($_=readdir(TOPDIR)){ print "$_\n"; }
This will read the _closed_ directory handle, without an error, if invoked as % perl test_file (where test_file) contains the above code.

But, I just discovered that if I chmod 0755 test_file, the code fails without a warning when invoked directly. So, I'm more confused than ever. What is happening here?

mkmcconn

Replies are listed 'Best First'.
Re: read closed directory handle?
by KM (Priest) on Jan 27, 2001 at 02:41 UTC
    You did a close() on a filehandle which is a directory. You need closedir().

    Cheers,
    KM

Re: read closed directory handle?
by lemming (Priest) on Jan 27, 2001 at 02:42 UTC
    You're closing the FILEHANDLE with close. I don't think a warning is generated when trying to close a directory handle.
    If you use closedir, you'll wind up with nothing printed.

    Update: It doesn't hurt to check if you successfully close file or directory handles. That would show the error with the close, instead of closedir.
    My guess on why warnings and strict didn't show anything is that you used the variables involved, but that's only a guess.
    readline will bring up a warning on a closed filehandle, but readdir doesn't seem to care that's it tries reading a closed directory handle.
Re: read closed directory handle?
by mkmcconn (Chaplain) on Jan 27, 2001 at 03:01 UTC

      Thanks to KM and lemming for the speedy reply. I didn't realize that I couldn't resubmit the post, or I would have cleaned up the errors I made in testing the code as posted, and I would have rephrased the question: "Why didn't this do what I expect". It will, of course, run when invoked directly.

      The point my two helpers made, is the lesson to take away: that close(FILEHANDLE) and closedir(DIRHANDLE) are not the same thing, FILEHANDLE and DIRHANDLE have separate namespaces (and thou shalt thoroughly test all operations, with warnings)
      Thanks again, brethren.

    mkmcconn

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://54657]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2024-04-20 04:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found