问题
if (-e "$ENV{MYHOME}/link") {
system("rm $ENV{MYHOME}/link");
}
This is the code being used to check if a symlink exists and remove it if it does.
I am tracking a bug where this code does not work. I have not been able to figure it out as of now, but what is happening is that this code is unable to remove the symlink, which results in a 'File exists' error down the line.
I wanted to check if there is some fundamental flaw with this technique? I also read about http://perldoc.perl.org/functions/unlink.html but would like to know if the current approach is not recommended due to some reason?
回答1:
Just use:
if ( -l "$ENV{MYHOME}/link" ) {
unlink "$ENV{MYHOME}/link"
or die "Failed to remove file $ENV{MYHOME}/link: $!\n";
}
If the unlink fails, it'll say why. The -l
asks if the target is a link. The -e
asks if the file exists. If your link is to a non-existent file, it'll return false, and your code would fail to remove the link.
回答2:
Your code will only have the permissions of the user it is running under. Is it possible that the symlink is owned by another user and not writable?
Also, there is always the possibility that $ENV{MYHOME} does not contain what you think it does...
回答3:
Respective operating systems have its own errno.h
. I would use Errno.pm
to handle each errors.
use Errno;
use File::Spec;
my $dir = File::Spec->catfile($ENV{MYHOME}, 'link');
if (!unlink $dir) {
if ($! == Errno::ENOENT) {
die "Failed to remove '$dir'. File doesn't exist:$!";
}
}
来源:https://stackoverflow.com/questions/9074005/how-to-check-and-delete-a-symlink-if-it-exists-using-perl