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] ){
    open( nofile, '>>', 'meanint.csv' );
    print nofile "$mean_data_sorted[$i]" . "," . "$j" . "\n";
    close nofile;

**real output - **

**the output i want - **

5 Years
Discussion Span
Last Post by 2teez

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 by 2teez

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.