作者frank1983 (What?)
看板Perl
标题Re: [问题] 档案复制
时间Mon Apr 20 15:43:43 2009
※ 引述《yanganto (双剑‧日光灯)》之铭言:
: 因为要在很多个档案中挑出我需要的档案,并且复制到另外一个资料夹,然後须要挑的
: 档案在一个htm的档案里面有写。
: 我利用一个array去选择要挑的档案,结果复制的档案会一个有内容一个没内容这样交替
: 不知道错误在哪里,可以麻烦板上高手指证一下吗?谢谢
: 刚开始学perl,写的有点乱,不知道有没有比较简洁一点的方法^^"
: 後来code改成这样,但是还是会一个有抓到一个没抓到这样@@",不知道有没有人能指导
: 一下,谢谢
: use strict;
: my @list;
: my $txt;
: open(L,'/Users/yanganto/Desktop/list.txt');
: while(<L>){
: $txt = $_;
: chomp($txt);
: @list = (@list,$txt);
: }
: my $i=0;
: my $file;
: for($i=0;$i<=413;$i++){
: $file = glob("/Users/yanganto/Desktop/Minimization/$list[$i]/Output/*.msv");
: system("cp $file /Users/yanganto/Desktop/5Cal/");
: }
因为 glob() 可能回传一个以上相符的档名
所以单纯使用 $file = glob(...) 会只得到第一个相符的档名
请参考
http://perldoc.perl.org/functions/glob.html
此外,在 for loop 的 413 可改为 $#list 比较安全
下面是我改写的版本,注解包含我这样写的原因,
希望对你有帮助^^
#!/usr/bin/perl
use warnings;
use strict;
use File::Copy;
our $list = '/Users/yanganto/Desktop/list.txt';
open (L, $list) or die "cannot open file '$list'\n";
our $basedir = '/Users/yanganto/Desktop';
while (<L>) { # 使用 loop,而不是一次将所有的 list 载入
chomp;
my $dir = "$basedir/Minimization/$_/Output";
next if !-d $dir;
# 先移至 $dir 工作目录,这是预防 $dir 包含 glob()
# 所使用的特殊字元 (如 []),造成 glob("$dir/*.msv")
# 输出错误的结果
chdir $dir;
# glob() 可能回传一个以上的档名
# 请参考
http://perldoc.perl.org/functions/glob.html
while (my $file = glob("*.msv")) {
my $newfile = "$basedir/5Cal/$file";
# 避免覆盖相同档名的档案
die "file '$newfile' exists\n" if -e $newfile;
copy $file, $newfile
or die "cannot copy file '$file' to '$newfile': $!\n";
}
}
close L;
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.230.108
1F:推 yanganto:感谢你...我试试:) 04/20 19:14
2F:推 yanganto:耶...解决了太感谢你了:) 04/20 19:23
3F:→ kornelius:其实你用 </path/to/*.msv> 应该也不会有问题才对 (?) 04/20 20:02
4F:→ kornelius:或者直接用 File::Find::Rule 04/20 20:04