Perl script to read a csv file from a particular r

2019-09-28 06:05发布

I have a CSV file my.csv with this content:

abc,yyy

efg,zzz

zsc,vvv

uvw,ggg

Depending upon the value in variable $X I need to read from that particular value until the end of the file. For example:

If $X = efg, the output would be:

efg,zzz

zsc,vvv

uvw,ggg

For $X = zsc:

zsc,vvv

uvw,ggg

This is the script I developed, which reads in a CSV file's whole content and displays it:

use strict;
use warnings;

open(my $data, '<', $file) or die "Could not open '$file' $!\n";

while (my $line = <$data>) {  
    chomp $line; 
    my @field = split "," , $line;
    print "$field[0] $field[1]";
}

Please help me with a script to display the above mentioned scenario.

2条回答
闹够了就滚
2楼-- · 2019-09-28 06:49

This solution skips lines 1 to the matching text, if (1 .. /\b$start_word\b/) and prints all lines from the matching text, to the end of the file.

#!/usr/bin/perl
use strict;
use warnings;

my $start_word = 'efg';
my @data;

while (<DATA>) {
    chomp;
    if (1 .. /\b$start_word\b/) {
        #print if /\b$start_word\b/;
        @data = [split /,/] if /\b$start_word\b/;
    }
    else {
        #print;
        push @data, [split /,/];
    }
}

# Do something with @data

__DATA__
abc,yyy
efg,zzz
zsc,vvv
uvw,ggg
查看更多
一纸荒年 Trace。
3楼-- · 2019-09-28 06:53

If you just want to print lines where the first field is equal or larger than a specified value (e.g., $X), use a condition:

if ($field[0] >= $X) { 
    print ... 
}
查看更多
登录 后发表回答