Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy symbolic links in Perl?

Tags:

symlink

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

like image 890
splintor Avatar asked Jan 07 '09 12:01

splintor


2 Answers

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

like image 131
Alnitak Avatar answered Nov 07 '22 18:11

Alnitak


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

like image 22
innaM Avatar answered Nov 07 '22 18:11

innaM