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

Perhaps I've been working too many hours, or not coding enough perl, but... If I want to check the contents of a directory for symbolic links, and verify that all the links actually point to existing files, does anyone see anything that I should watch out for in the following code:
#!/opt/perl5/bin/perl $THISDIR="links/"; opendir THISDIR, "$THISDIR" or die "AACK: $!"; @allfiles = grep !/^\./, readdir THISDIR; # get rid of .* files closedir THISDIR; foreach $link (@allfiles){ $rc=readlink "$THISDIR$link"; !$rc and print "READLINK err: $link\n"; -f $rc or print "File $rc does not exist\n"; }

Replies are listed 'Best First'.
Re: verifying symbolic links
by no_slogan (Deacon) on Jul 25, 2001 at 03:06 UTC
    Your code will fail on relative symbolic links, for example:
    /home/me/links/foo -> ../bar
    Resolving symlinks is trickier than it seems. Let the operating system do it for you instead of trying to do it yourself with readlink.
    print "Bad link: $link -> $rc\n" if -l $link && ! -e $link;
      UPDATE

      Somehow my books forgot to list the "-l" file test operator. Thanks for the tip. Based on your tip, here's my new code. I need to do some additional formatting, but I think it will work quite nicely.

      #!/opt/perl5/bin/perl $THISDIR="links/"; opendir THISDIR, "$THISDIR" or die "AACK: $!"; @allfiles = grep !/^\./, readdir THISDIR; closedir THISDIR; foreach $link (@allfiles){ $rc=readlink "$THISDIR$link"; if ((-l "$THISDIR$link") && ! -e $rc){ print "Target for link \[$link\]:\t does not exist\n"; }elsif (-l "$THISDIR$link" && -e $rc){ print "Target for link \[$link\]:\t $rc\n"; }else{ print "File \[$link\] found in links directory\n"; } }
      /UPDATE
(MeowChow) Re: verifying symbolic links
by MeowChow (Vicar) on Jul 25, 2001 at 03:40 UTC
    From the shell:
    find . -follow -type l
    Sprinkle in -maxdepth to taste.
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
      Thanks for the fresh viewpoint. While I think I see what you're thinking, you should be aware that most systems (ok, HP and Solaris) recommend not using -follow with -type l.

      (from the man page) This expression should not be used with the -type l expression.

Re: verifying symbolic links
by merlyn (Sage) on Jul 25, 2001 at 17:52 UTC