Perl中的文件操作

Ebi*_*ser 1 csv perl text

我有一个简单的.csv文件,我想从写入新文件中提取数据.

我写一个读取文件的脚本,读取每一行,然后按不同的顺序拆分和构造列,如果.csv中的行包含'xxx' - 不要将行输出到输出文件.

我已经设法在一个文件中读取,并创建了一个辅助文件,但是对于Perl是新手,并且仍在尝试计算命令,以下是我为了掌握Perl而编写的测试脚本,并且想知道我是否可以对我需要的东西嗤之以鼻? -

open (FILE, "c1.csv") || die "couldn't open the file!";
open (F1, ">c2.csv") || die "couldn't open the file!";

#print "start\n";

sub trim($);

sub trim($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}

$a = 0;
$b = 0;
while ($line=<FILE>)
{
    chop($line);

    if ($line =~ /xxx/)
    {
        $addr = $line;
        $post = substr($line, length($line)-18,8);
    }
    $a = $a + 1;
}

print $b;
print " end\n";
Run Code Online (Sandbox Code Playgroud)

任何帮助深表感谢.

Fra*_*o R 9

要操作CSV文件,最好使用CPAN中的一个可用模块.我喜欢Text :: CSV:

use Text::CSV;

my $csv = Text::CSV->new ({ binary => 1, empty_is_undef => 1 }) or die "Cannot use CSV: ".Text::CSV->error_diag ();

open my $fh, "<", 'c1.csv' or die "ERROR: $!";
$csv->column_names('field1', 'field2');
while ( my $l = $csv->getline_hr($fh)) {
    next if ($l->{'field1'} =~ /xxx/);
    printf "Field1: %s Field2: %s\n", $l->{'field1'}, $l->{'field2'}
}
close $fh;
Run Code Online (Sandbox Code Playgroud)

  • Lambo:您需要先安装`Text :: CSV`模块.尝试按照以下说明从PPM安装它:http://docs.activestate.com/activeperl/5.10/faq/ActivePerl-faq2.html (2认同)