我有一个Perl脚本,我知道它会创建文件的硬链接,我希望改为创建符号链接,有些Perl-savvy人可以帮我修改脚本吗?我只做PHP,所以我可以阅读循环逻辑等但不确定Perl如何与文件系统交互。
我假设它在循环中开始@第62行:foreach my $file(@to_add) {...
#!/usr/bin/perl
use strict;
use warnings;
use JSON qw( decode_json );
use Data::Dumper;
my $hashkey = 'myKey';
my $data_folder = '/jail/glftpd/site';
my $player_folder = '/var/mediaplayers';
my $mediaplayersurl = "myRoute";
sub filesInFolder {
my ($path) = @_;
my @files = ();
if(opendir SCANDIR, $path) {
push @files, grep !/^\./ && -f "$path/$_", readdir SCANDIR;
closedir SCANDIR;
}
return @files;
}
my $json = `wget --no-check-certificate --header "keyFile: $hashkey" -q -O - $mediaplayersurl`;
die "Failed to retrieve $mediaplayersurl!", unless defined $json;
my $data = decode_json($json);
# print Dumper $data;
foreach my $player(@$data) {
my $sync_folder = $player_folder."/".$player->{companyName}."/".$player->{mediaPlayer};
my $source_folder = $data_folder."/".$player->{companyName};
print "Preparing ".$player->{companyName}."/".$player->{mediaPlayer}."\n";
unless(-d $source_folder) {
print STDOUT "Source folder '$source_folder' does not exist, doing nothing.\n";
next;
}
unless(-d $sync_folder) {
system("mkdir", "-p", $sync_folder);
}
my @existing = filesInFolder($sync_folder);
my %existing = map {$_, => 1} @existing;
my @videos = ();
foreach(@{$player->{'videos'}}) {
push @videos, $_;
}
my %videos = map {$_, => 1} @videos;
my @to_add = grep {not $existing{$_}} @videos;
my @to_del = grep {not $videos{$_}} @existing;
foreach my $file(@to_add) {
my $source_file = $source_folder."/".$file;
my $target_file = $sync_folder."/".$file;
unless(-e $source_file) {
print STDERR "Failed to create link to '$source_file', file does not exist.\n";
next;
}
if(system('ln', $source_file, $target_file) != 0) {
print STDERR "Failed to create link from '$target_file' to '$source_file'.\n";
}
else {
print "Linked '$target_file' to '$source_file'.\n";
}
}
foreach my $file(@to_del) {
my $target_file = $sync_folder."/".$file;
if(system('rm', $target_file) != 0) {
print STDERR "Failed to remove file link '$target_file'.\n";
}
else {
print "Removed link '$target_file'.\n";
}
}
}
答案 0 :(得分:2)
你不需要掏出来。 Perl有一个内置来创建symlink
。你可以替换所有这些:
if(system('ln', $source_file, $target_file) != 0) {
print STDERR "Failed to create link from '$target_file' to '$source_file'.\n";
}
else {
print "Linked '$target_file' to '$source_file'.\n";
}
使用:
my $link_created = symlink $src_file, $link_name or die $!;
print "symlink created ok\n" if $link_created;