Perl script to read a csv file from a particular row to end of file

杀马特。学长 韩版系。学妹 提交于 2019-12-27 07:02:36

问题


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.


回答1:


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



回答2:


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 ... 
}


来源:https://stackoverflow.com/questions/12212325/perl-script-to-read-a-csv-file-from-a-particular-row-to-end-of-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!