如何打印出新文件perl中的输出

时间:2012-09-14 11:17:14

标签: perl

如何在目录中打印变量$ newFile的输出?我如何使用'cp'来做到这一点? 修改后,我的代码如下所示:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use File::Copy 'cp';

# binmode(STDOUT, ":utf8") ;
# warn Dumper \@repertoire;

my @rep= glob('/home/test/Bureau/Perl/Test/*'); # output to copy in this dir
foreach my $file (@rep)
{
    open(IN, $file) or die "Can't read file '$file' [$!]\n";
    while (<IN>)
    {
    my ($firstCol, $secondCol) = split(/","/, $_); 

    $firstCol =~ s/http:\/\//_/g;
    $secondCol =~ s/\(.+\)/ /ig;
    my $LCsecondCol = lc($secondCol);
    chomp($secondCol);
    chomp($LCsecondCol);
    my $newFile = "$firstCol:($secondCol|$LCsecondCol);";
    $newFile =~ s/=//g;
    print "$newFile\n";

    }
    close(IN);
}

1 个答案:

答案 0 :(得分:4)

你的程序即使编译还有很长的路要走。你应该注意这些细节

  • use strict到位的情况下,您必须在首次使用时声明所有变量。变量@files$file$newFile未声明,因此您的程序无法编译

  • 标量上下文中的
  • glob返回与模式匹配的 next 文件名,并且用于while循环。要获得与您应该分配给数组的模式匹配的所有文件,并从注释掉的warn语句中看起来您的代码就像那样

  • 您应该使用词法文件句柄和open的三参数形式。干得好,检查open的状态并将$!放入die字符串

  • 您的$file =~ ...行看起来应该是替换,并且末尾的括号应该是分号

  • 您已使用File::Copy,但随后使用system复制文件。您应该避免在任何方便的地方进行炮轰,并且由于File::Copy提供了cp功能,您应该使用它

更接近代码的工作版本的内容将如下所示

use strict;
use warnings;

use File::Copy 'cp';

while (my $fileName = glob '/home/test/Bureau/Infobox/*.csv') {

    my @files = do {
        open my $in, '<', $fileName or die "Can't read file '$fileName' [$!]\n";
        print "$fileName\n" ;
        <$in>;
    };

    foreach my $file (@files) {
        my $newFile = $file =~ s/(\x{0625}\x{0646}\b.+?)\./[[    ]]/gr;
        cp $file, $newFile;
    }
}