How to extract row data from a csv file using perl?

I have a csv file like

Genome Name,Resistance_phenotype,Amikacin,Gentamycin,Aztreonam AB1,,Susceptible,Resistant,Resistant AB2,,Susceptible,Susceptible,Susceptible AB3,,Resistant,Resistant,NA

I need to fill 2nd coloumn i.e. Resistant phenotype with MDR, XDR and susceptible. for which I have to match antibiotic resistance profile like if in first row gentamycin & antreanam both are resistant the 2nd coloumn will be filled with MDR and in 3nd row if all 3 are susceptible the 2nd coloumn of 3rd row will be filled with susceptible.

I have written a code mentioned below which only display columns of the csv file. I got stuck what to do futher.

#!/usr/bin/perl
use strict;
use warnings;
my $file = 'text.csv';
my @data;
open(my $fh, '<', $file) or die "Can't read file '$file' [$!]\n";
while (my $line = <$fh>) {
    chomp $line;
    my @fields = split(/,/, $line);
    print $fields[0], "\n";
    #print $fields[1], "\n";
}
close $file;

Genome Name,Resistance_phenotype,Amikacin,Gentamycin,Aztreonam AB1,MDR,Susceptible,Resistant,Resistant AB2,Susceptible,Susceptible,Susceptible,Susceptible AB3,MDR,Resistant,Resistant,NA

1 answer

  • answered 2019-08-18 15:39 brian d foy

    Use the Text::CSV_XS module. Read a line, assign the right value to the that column, then print it again. In your sample code, you were only writing one column instead of all of them; the module will handle all of that for you:

    use Text::CSV_XS;
    
    my $csv = Text::CSV_XS->new;
    
    # replace *DATA and *STDOUT with whatever filehandles you want
    # to read then write.
    while( my $row = $csv->getline(*DATA) ) {
        $row->[1] = 'Some value';
        $csv->say( *STDOUT, $row );
        }
    
    
    __DATA__
    Genome Name,Resistance_phenotype,Amikacin,Gentamycin,Aztreonam
    AB1,,Susceptible,Resistant,Resistant
    AB2,,Susceptible,Susceptible,Susceptible
    AB3,,Resistant,Resistant,NA
    

    The output is:

    "Genome Name","Some value",Amikacin,Gentamycin,Aztreonam
    AB1,"Some value",Susceptible,Resistant,Resistant
    AB2,"Some value",Susceptible,Susceptible,Susceptible
    AB3,"Some value",Resistant,Resistant,NA