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

a aa b cc d dd ee f gg j kk this is my csv file.. and my answer should be like a,b,d,f,j Aa,cc,dd,ee,gg,kk can any one help me with this?? if u can pls post ur answers
  • Comment on i need to join two fields in .csv file??

Replies are listed 'Best First'.
Re: i need to join two fields in .csv file??
by CountZero (Bishop) on Mar 14, 2013 at 07:38 UTC
    Use Text::CSV to read your CSV file and extract the fields. Then assemble the output line using the Text::CSV::combine method and print the output to your new file.

    Take some hints from the followingexample:

    use Modern::Perl; use Text::CSV; my $csv = Text::CSV->new() or die "Cannot use CSV: " . Text::CSV->erro +r_diag(); open my $fh_in, '<', "test.csv" or die "test.csv: $!"; open my $fh_out, '>', "test_new.csv" or die "test_new.csv: $!"; while ( my $line = <$fh_in> ) { my $status = $csv->parse($line); my ( $field1, $field2, $field3, $field4 ) = $csv->fields(); $status = $csv->combine( $field3, $field2, $field1, $field4 ); my $output_string = $csv->string(); print $fh_out $output_string; }

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics

      PLEASE advice using getline () instead of perl's internal getline:

      open my $fh_in, "<", "test.csv" or die "test.csv: $!"; open my $fh_out, ">", "test_new.csv" or die "test_new.csv: $!"; my $csv_in = Text::CSV->new ({ binary => 1, auto_diag => 1 }); my $csv_out = Text::CSV->new ({ binary => 1, auto_diag => 1, eol => "\ +n" }); while (my $row = $csv_in->getline ($fh_in)) { $csv_out->print ($fh_out, [ @{$row}[2,1,0,3] ]); }

      Enjoy, Have FUN! H.Merijn
Re: i need to join two fields in .csv file??
by Ratazong (Monsignor) on Mar 14, 2013 at 07:49 UTC

    Hi!

    How would you do it manually? You would probably

    • read the file (into a list in "memory")
    • sort that list by lenght of the entries and alphabetically
    • write down the sorted list
    So you have just to do that in perl. You might think of arrays, open, sort and print.

    HTH, Rata

Re: i need to join two fields in .csv file??
by Anonymous Monk on Mar 14, 2013 at 07:44 UTC