How to check and remove a symlink, if one exists, using Perl?

if (-e "$ENV{MYHOME}/link") { system("rm $ENV{MYHOME}/link"); } 

This is the code used to verify the existence of a symbolic link and remove it, if possible.

I am tracking an error where this code does not work. I have not been able to figure it out yet, but what happens is that this code cannot delete the symbolic link, which leads to the "File exists" error by line.

I wanted to check if there is any fundamental flaw in this technique? I also read about http://perldoc.perl.org/functions/unlink.html , but would like to know if for some reason the current approach is not recommended?

+8
perl
source share
3 answers

Just use:

 if ( -l "$ENV{MYHOME}/link" ) { unlink "$ENV{MYHOME}/link" or die "Failed to remove file $ENV{MYHOME}/link: $!\n"; } 

If the communication failure goes off, he will say why. -l asks if the target is a link. -e asks if the file exists. If your link is linked to a non-existent file, it will return false, and your code will not be able to delete the link.

+20
source share

Your code will only have permissions of the user on which it is running. Is it possible that the symbolic link belongs to another user and is not writable?

In addition, there is always the possibility that $ ENV {MYHOME} does not contain what you think it does ...

0
source share

Corresponding operating systems have their own errno.h . I would use Errno.pm to handle each error.

 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:$!"; } } 
0
source share

All Articles