How do I copy symbolic links in Perl?

2019-04-29 23:16发布

问题:

How do I copy a symbolic link (and not the file it points to) in a Perl program while preserving all of the symbolic link attributes (such as owner and permissions)?

回答1:

In Perl you can use the readlink() function to find out the destination of a symlink.

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).

Actually setting the ownership on the new symlink can't be done without extra help as Perl doesn't expose the lchown() system call. For that you can use the Perl Lchown module from CPAN.

Assuming sufficient permissions (nb: unchecked code)

 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



回答2:

The module File::Copy::Recursive takes care of that. By default it will copy symlinks and try to preserve ownership.



回答3:

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 symlink