i was trying to create csv file by appending variables using print function
what's wrong with this code why this prints ","."$j" to a new line

**code is here - **

while( $i < 1000 ){
    $j = 1;
    while( $mean_data_sorted[$i] == $mean_data_sorted[$i+1] ){
        $i++;
        $j++;
    }
    open( nofile, '>>', 'meanint.csv' );
    print nofile "$mean_data_sorted[$i]" . "," . "$j" . "\n";
    close nofile;
    $i++;
}

**real output - **
-0.667
,33
-0.663
,23
-0.656
,19
-0.655
,32
-0.619
,23

**the output i want - **
-0.667,33
-0.663,23
-0.656,19
-0.655,32
-0.619,23

There's nothing wrong with the code per se. From your output it looks like $mean_data_sorted[$i] is a string that ends with a line break. So the quickest way to fix your issue would be to chomp @mean_data_sorted before you iterate over it.

Depending on how you create mean_data_sorted, it might also be possible to simply not put an line breaks in there in the first place.

Hi rajesrmbioinfo,
I know there are more than one way to do it in Perl, but so many ways are not efficient and effective.
Am glad you have your coding working fine, but there are some things I believe you should also put in place.

  1. Your open function should handle an error case, what if, the file doesn't exist?
    So, you should have open (my $fh,'>>',filename) || die "can't open file:$!;" OR write it like:
    open my $fh,'>>',filename or die "can't open file: $!";

  2. Use a lexical scope filehandle like I did in number 1,

  3. Why use two while loop? The second while loop, can be replaced an If statement,
  4. To generate a CSV file, though you can write yours, just like you did. But using module that
    has been used and tested by many can come in handy here.
    You can use either Text::CSV or Text::CSV_XS

Hope this helps.

Edited 3 Years Ago by 2teez

This article has been dead for over six months. Start a new discussion instead.