【发布时间】:2010-08-13 10:20:25
【问题描述】:
今天早上,我和我的朋友讨论并编写了以下代码。这个 Perl 脚本背后的想法是创建目录结构并将文件复制到相应的目录。
#!/usr/bin/perl
use File::Path;
use File::Copy;
use Path::Class;
use File::Basename qw/dirname/;
my $src = "/Vijay/new.txt";
unless (open(MYFILE, "file1")) {
die ("cannot open input file file1\n");
}
$line = <MYFILE>;
while ($line ne "") {
print ($line);
mkdir_and_copy($src,$line);
$line = <MYFILE>;
}
sub mkdir_and_copy {
my ($from, $to) = @_;
my($directory, $filename) = $to =~ m/(.*\/)(.*)$/;
print("creating dir $directory");
system "mkdir -p $directory";
print("copying file $from to $to");
system "cp -f $from $to";
return;
}
上面这段代码创建了目录结构,但是无法将文件复制到相应的目录。请告诉我们,我们到底哪里错了?
file1 的内容:
test/test1/test2/test.txt
new.txt 的内容:
Shell/Test/test1/test1.txt
Shell/Test/test2/test2.txt
Shell/Test/test3/test3.txt
输出:
> ./mypgm.pl
test/test1/test2/test.txt
creating dir test/test1/test2/copying file /Vijay/new.txt to test/test1/test2/test.txt
cp: cannot access /Vijay/new.txt: No such file or directory
>
目录Vijay有文件new.txt,上面的内容。
提前致谢,
维杰
大家好,
我刚刚修改了我的代码。请参考下面的代码部分。
#!/usr/bin/perl
use File::Path;
use File::Copy;
use File::Basename qw/dirname/;
my $src = "./Vijay/new.txt";
unless (open(MYFILE, "file1"))
{
die ("cannot open input file file1\n");
}
$line = ;
while ($line ne "")
{
print ($line); print("\n");
mkdir_and_copy($src,$line);
$line = ""; }
sub mkdir_and_copy
{
my ($from, $to) = @_;
my($directory, $filename) = $to =~ m/(.\/)(.)$/;
$temp = $directory.$filename;
print("Creating dirrectory $directory \n");
if(! -d $directory)
{
mkpath($directory) #or die "Failed to create path";
}
printf("From: $from \n");
printf("To: $temp \n");
copy($from,$temp) or die "Failed to Copy";
return;
}
现在,它会创建准确的目录结构并将文件复制到相应的目录。你能告诉我,上面的代码是否正确?
【问题讨论】:
-
可以添加输出吗?
-
阅读一两本书,了解您正在使用的语言以及可能的一般编程。严重地。您的脚本中没有一行是正确编写的。如果这条评论伤害了你的感情,我很抱歉,但这是你需要改进的地方。
-
file1的内容:test/test1/test2/test.txt new.txt的内容:Shell/Test/test1/test1.txt Shell/Test/test2/test2.txt Shell/Test/test3 /test3.txt 输出:> ./mypgm.pl test/test1/test2/test.txt 创建目录 test/test1/test2/将文件 /Vijay/new.txt 复制到 test/test1/test2/test.txt cp:不能访问/Vijay/new.txt:没有这样的文件或目录>目录'Vijay'有文件new.txt与上述内容。
-
@msv:很痛。但是,对于初学者和浪费了所有机会的人来说,值得这样做:(谢谢。
-
当我开始重构这个程序时,我注意到它的编写方式是无可救药的。我不知道你是想对
/Vijay/new.txt的内容进行操作还是复制文件本身——就像现在一样,程序两者都没有。请edit the question 并简单地添加您要实现的算法的低级描述。