How do I copy symbolic links in Perl?

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

Thanks, splintor


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


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

链接地址: http://www.djcxy.com/p/56766.html

上一篇: 在Mac OSX 10.5中,它找不到我的终端命令sudo,find等

下一篇: 如何复制Perl中的符号链接?