-d pathname will test if pathname exists and is a directory. If you want more resolution, you can say
if (-d $pathname) { # $pathname exists and is a directory # ... } elsif (-e _) { # $pathname exists, but is NOT a directory # ... } else { # $pathname doesn't even exist # ... }
Note the use of the special pseudo-filehandle _: it's used to test the last filehandle tested. See perlfunc for more details of this.

In any case, testing for existence of a file or a directory is often indicative of a bug. It is almost always better to try to get what you need in a single operation. For instance, instead of saying

if (-d $d) { open FILE, "$d/$f" or die "Open failed"; } else { die "No directory $d"; }
do just the open:
open FILE, "$d/$f" or die "Open failed";

Let the operating system make sure your path is OK. The first way is subject to an insiduous race condition: directory $d could be created between the test -d $d and the error message, and the error message would be wrong. This is not too bad; but if some more complex error handling were used, it would be likely to break.

So try not to test if you can do something with -X; just try to do it. If you can't, the OS will let you know.


In reply to Re: How to test if a directory exists? by ariels
in thread How to test if a directory exists? by newbie00

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.