开发者

File manipulation in Perl

开发者 https://www.devze.com 2023-03-13 01:35 出处:网络
I have a simple .csv file that has that I want to extract data out of a write to a new file. I to write a script that reads in a file, reads each line, then splits and structures the columns in a dif

I have a simple .csv file that has that I want to extract data out of a write to a new file.

I to write a script that reads in a file, reads each line, then splits and structures the columns in a different order, and if the line in the .csv contains 'xxx' - dont output the line to output file.

I have already managed to read in a file, and create a secondary file, however am new to Perl and still trying to work out the commands, the following is a test script I wrote to get to grips with Perl and was wondering if I could aulter this to to what I need?-

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";

Any help is much appreciated.


To manipulate CSV files it is better to use one of the available modules at CPAN. I like 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;


If you need do this only once, so don't need the program later you can do it with oneliner:

perl -F, -lane 'next if /xxx/; @n=map { s/(^\s*|\s*$)//g;$_ } @F; print join(",", (map{$n[$_]} qw(2 0 1)));'

Breakdown:

perl -F, -lane
     ^^^   ^ <- split lines at ',' and store fields into array @F

next if /xxx/;    #skip lines what contain xxx

@n=map { s/(^\s*|\s*$)//g;$_ } @F;
    #trim spaces from the beginning and end of each field
    #and store the result into new array @n

print join(",", (map{$n[$_]} qw(2 0 1)));
    #recombine array @n into new order - here 2 0 1
    #join them with comma
    #print

Of course, for the repeated use, or in a bigger project you should use some CPAN module. And the above oneliner has much cavetas too.

0

精彩评论

暂无评论...
验证码 换一张
取 消