如何使用 Perl 检查和删除符号链接(如果存在)? [英] How to check and delete a symlink if it exists, using Perl?

查看:87
本文介绍了如何使用 Perl 检查和删除符号链接(如果存在)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

我想检查一下这种技术是否存在一些根本性缺陷?我还阅读了关于 http://perldoc.perl.org/functions/unlink.html但想知道是否由于某种原因不推荐当前的方法?

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?

推荐答案

只需使用:

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

如果取消链接失败,它会说明原因.-l 询问目标是否为链接.-e 询问文件是否存在.如果您的链接指向一个不存在的文件,它将返回 false,并且您的代码将无法删除该链接.

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.

这篇关于如何使用 Perl 检查和删除符号链接(如果存在)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆