friedo points out -l. I'll add two more pieces: using lstat (which is what -l uses i under the covers), which gets way too complicated, and using readlink to read the symlink.

Note that while you can use the "_" special variable for the -X operators, you need to be careful when you're involving the -l. You can't do if (-d $file && -l _). That will always return false. You must reverse that: if (-l $file && -d _). The reason is that the -d check (and everything except -l) will use stat which follows symlinks reading the underlying file, directory, device, FIFO, whatever. That will never be a symlink (unless it points to a nonexistant entity). Of course, if it points to a nonexistant entity, it won't be a directory ;->

if (-d $file && -l $file) should work fine, albeit the tiniest bit more expensive than if (-l $file && -d _).

Also be careful with readlink. It can be awfully tricky to follow symlinks the way that the OS does. Symlinks to symlinks to files inside symlink'd directories ... it's really convoluted. You're probably better off using stat (not lstat) and using the first two fields (dev and ino) as hash keys to keep track of whether you've seen it or not. This will actually also catch hardlinked files which you probably aren't even thinking about ;-)

{ my %seen; sub have_seen_file { my $file = shift; my ($dev, $ino) = stat($file); $seen{$dev}{$ino}++; } sub reset_seen_files { %seen = () } }
Or something like that.

Update: tye is right - I normally actually use this shortcut as "if (-l $file || -d _)" which, of course, is not what the OP wanted.


In reply to Re: Detecting if a folder is a symbolic link by Tanktalus
in thread Detecting if a folder is a symbolic link by ralphch

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.