Perl script to read a csv file from a specific line to the end of the file

I have a CSV file my.csvwith this content:

abc,yyy

efg,zzz

zsc,vvv

uvw,ggg

Depending on the value in the variable, $XI need to read from this particular value to the end of the file. For instance:

If $X = efg, the output will be:

efg,zzz

zsc,vvv

uvw,ggg

For $X = zsc:

zsc,vvv

uvw,ggg

This is a created script that reads all content in a CSV file 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 the script to display the above script.

-4
source share
2 answers

This solution skips line 1 into the corresponding text, if (1 .. /\b$start_word\b/)and prints all lines from the corresponding 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
+1
source

, (, $X), :

if ($field[0] >= $X) { 
    print ... 
}
0

All Articles