http://www.perlmonks.org?node_id=1038736

MynameisAchint has asked for the wisdom of the Perl Monks concerning the following question:

hey

I have written this code to extract columns from a csv file , it is working fine , but in last line there is a \n which I need to remove . please tell me where to chomp or any other way to remove this \n

sub column_segregation_Spec_values columns of csv file { $column_number=$_[0]; c my $size; my @array_A1=(); my @array_A2=(); my $column_separator = ","; $column_number--; + my $file="Working_On.csv"; open(FILE,"<","$file"); my @lines=<FILE>; close FILE; foreach my $line (@lines) { my @columns = split(/$column_separator/,"$line"); push @array_A2, $columns[$column_number]; } return (@array_A2);

Replies are listed 'Best First'.
Re: removing \n with for each
by choroba (Cardinal) on Jun 13, 2013 at 13:32 UTC
    If you want to remove the newline from all the lines in the array, use
    chomp @lines;

    If you want to delete the newline only from the last line, use

    chomp $lines[-1];
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: removing \n with for each
by Happy-the-monk (Canon) on Jun 13, 2013 at 13:32 UTC

    my @lines=<FILE>;

    chomp(my @lines=<FILE>); # should remove your newlines.

    Cheers, Sören

    (hooked on the Perl Programming language)

Re: removing \n with for each
by davido (Cardinal) on Jun 13, 2013 at 15:38 UTC

    I have written this code to extract columns from a csv file ,

    Arrgghhhhhh! Noooooooooo! Text::CSV

    (Whew, that feels better.)

    Unless your goal is to learn how to write a CSV parser, don't write code to parse CSV files; it's been done (correctly) on CPAN.


    Dave

Re: removing \n with for each
by space_monk (Chaplain) on Jun 13, 2013 at 15:42 UTC

    Why bother extracting columns from a CSV file yourself when people have done it before? See Text::CSV_XS and its incredibly long list of relations.

    If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)