简体   繁体   English

如何在Perl中复制符号链接?

[英]How do I copy symbolic links in Perl?

如何在保留所有符号链接属性(例如所有者和权限)的同时复制Perl程序中的符号链接(而不是它指向的文件)?

In Perl you can use the readlink() function to find out the destination of a symlink. 在Perl中,您可以使用readlink()函数来查找符号链接的目标。

You can also use the lstat() function to read the permissions of the symlink (as opposed to stat() which will read the details of the file pointed to by the symlink). 您还可以使用lstat()函数来读取符号链接的权限(而不是stat() ,它将读取符号链接指向的文件的详细信息)。

Actually setting the ownership on the new symlink can't be done without extra help as Perl doesn't expose the lchown() system call. 实际上,如果没有额外的帮助,就无法在新的符号链接上设置所有权,因为Perl不公开lchown()系统调用。 For that you can use the Perl Lchown module from CPAN. 为此,您可以使用CPAN的Perl Lchown模块。

Assuming sufficient permissions (nb: unchecked code) 假设有足够的权限(nb:未经检查的代码)

 use Lchown;
 my $old_link = 'path to the symlink';
 my $new_link = 'path to the copy';

 my $dst = readlink($old_link);
 my @stat = lstat($old_link);

 symlink $dst, $new_link;
 lchown $stat[4], $stat[5], $new_link;  # set UID and GID from the lstat() results

You don't need to worry about the permissions on the symlink - they always appear as -rwxrwxrwx 您无需担心符号链接上的权限 - 它们始终显示为-rwxrwxrwx

The module File::Copy::Recursive takes care of that. 模块File :: Copy :: Recursive负责处理。 By default it will copy symlinks and try to preserve ownership. 默认情况下,它会复制符号链接并尝试保留所有权。

Depending on your use case regarding absolute vs. relative target paths, dir hierarchy etc., using link to create a hardlink to the symlink you want to copy might be enough already as well. 根据您关于绝对与相对目标路径,目录层次结构等的用例,使用链接创建要复制的符号链接的硬链接可能已经足够了。 No extra packages needed and creating hardlinks is supported by Perl on many platforms as well. Perl在许多平台上也不支持额外的包,并且支持创建硬链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM