You cannot create the links before both the source and target directories exist. So, postpone their creation to the end. The directories are processed from the shortest to the longest, so we always know the parent path exists.
You should also add a check that a link doesn't point outside of the given directory tree.
I created the following Makefile to experiment with your data:
And this was the script 1.pl:
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
use Path::Tiny qw{ path };
my $path = path(shift);
my $paths = $path->visit(
sub { $_[1]->{$_} = (-f) ? 'file'
: (-l) ? [readlink]
: (-d) ? 'dir'
: 'unknown' },
{ recurse => 1 }
);
my @links;
for my $found (sort { length $a <=> length $b } keys %$paths) {
if ('file' eq $paths->{$found}) {
say qq(cp '$found' "\$target/$found");
} elsif ('dir' eq $paths->{$found}) {
say qq(mkdir "\$target/$found");
} elsif (ref [] eq ref $paths->{$found}) {
my $to = path($paths->{$found}[0]);
$to = $to->relative(path($found)->absolute->parent)
if $to->is_absolute;
my $source = path('$target', $found);
push @links, qq(ln -s "$to" "$source");
}
}
say for @links;
It's just a toy. Use some of the ShellQuote modules to fix the filenames; but for the example given, it works.
map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
|