0

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 column 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 column will be filled with MDR and in 3nd row if all 3 are susceptible the 2nd column 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 further.

#!/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
  • Please upload the actual file somewhere and post a link. It will be useful to test and to see the solution in an acton. Commented Aug 18, 2019 at 14:48

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for your reply. This code is working but the problem is now I want to compare column values like if column 2nd and 3rd has Resistant value than column 1st will be filled by MDR and if both are susceptible than column Ist will be filled by susceptible.
@TinaSharma: If you have further questions, then it probably makes sense to post them separately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.