Linux – How to detect that a symlink is broken in Perl

linuxperlsymlink

I would like to remove a broken symlink in a directory using Perl.

In my mind I just had to list the file of a directory and test is this a symlink (-l) and if it returns false just unlink it.

But it appears that when using readir to list all files my broken symlinks are not recoganized as a file. Because my link is pointing to nothing I understand why.

Then : How can I detect if a symlink is broken in Perl ?

Thank you,

UPDATE

All the file in $myDir are symlinks, either valid or broken.
When I display @files I only get a list of valid symlink.

opendir DIR, $myDir;
my @files = grep(/$regexp/,readdir(DIR));
closedir DIR;
print "filenames : @files\n";

Best Answer

There are two main relevant system calls, stat() and lstat(). The lstat() call will tell you that it is a symlink (but on other files, behaves the same as stat()). This allows you to determine that the name is a symlink. The stat() system call follows a symlink to its end, and tells you about the file (or directory) at the end of the link. If the stat() call fails on the symlink, then the symlink is broken or you're trying to access a directory or file where you have no permission.

The Perl file test operators include -l to detect whether a name is a symlink. You can use the Perl functions stat and lstat explicitly. Between these, you should be able to sort out whether a symlink is broken or not - but you should probably plan to write a function to do the job.

You probably don't need to use the readlink Perl function. Beware the underlying system readlink() call; it does not return a null-terminated string!

It is interesting that neither Perl nor its POSIX module supports the realpath() function. However, the PathTools module does support it. If realpath fails, on a symlink, the symlink is non-functional (aka broken).