john.tm has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks I have a few scripts that convert an xlsx file to a tab seperated file, which then remove any commas, duplicates and then splits it by commas. (i do this to make sure users have not put any commas in a colomn) I then do some stuff. and then convert it back to an xlsx file. This has always worked fine. But instead of opening and closing files all the time i thought i would push the file to an array and then convert it to an xlsx at the end. Unfortunatly when i try and convert back to an xlsx file it is creating a newline in the space between the name. If i OUTPUT to a csv file then Open it and convert to an xlsx file it works fine.
#!/usr/bin/perl use strict; use warnings; use Spreadsheet::BasicRead; use Excel::Writer::XLSX; local $" = "'\n'"; open( STDERR, ">&STDOUT" ); #covert to csv my $xlsx_WSD = ( "C:\\Temp\\testing_file.xlsx"),, 1; my @csvtemp; if ( -e $xlsx_WSD ) { my $ss = new Spreadsheet::BasicRead($xlsx_WSD) or die; my $col = ''; my $row = 0; while ( my $data = $ss->getNextRow() ) { $row++; $col= join( "\t", @$data ); push @csvtemp, $col . "\n" if ( $col ne "" ); } } else { print " C:\\Temp\\testing_file.xlsx file EXISTS ...!!\n +"; print " please investigate and use the restore option i +f required !..\n"; exit; } ; my @arraynew; my %seen; our $Header_row = shift (@csvtemp); foreach (@csvtemp){ chomp; $_ =~ s/,//g; $_ =~ s/\t/,/g; # print $_ . "\n" if !$seen{$_}++ ; push @arraynew, $_ . "\n" if !$seen{$_}++ ; #remove any + dupes } #covert back to xlsx my $workbook = Excel::Writer::XLSX->new("C:\\Temp\\testing_filet.xlsx +"); my $worksheet = $workbook->add_worksheet(); my ( $x, $y ) = ( 0, 0 ); while (<@arraynew>) { my @list = split /,/; foreach my $c (@list) { $worksheet->write( $x, $y++, $c ); } $x++; $y = 0; } __DATA__ Animal keeper M/F Years START DATE FRH FSM GIRAFFE JAMES LE M 5 10/12/2007 Y HIPPO JACKIE LEAN F 6 11/12/2007 Y ZEBRA JAMES LEHERN M 7 12/12/2007 Y GIRAFFE AMIE CAHORT M 5 13/12/2012 Y GIRAFFE MICKY JAMES M 5 14/06/2007 Y MEERKAT JOHN JONES M 9 15/12/2007 v v LEOPPARD JIM LEE M 8 16/12/2002 unexpected result GIRAFFE JAMES LE M 5 10/12/2007 Y " HIPPO" JACKIE LEAN F 6 11/12/2007 Y " ZEBRA" JAMES LEHERN M 7 12/12/2007 Y " GIRAFFE" AMIE CAHORT M 5 13/12/2012 Y " GIRAFFE" MICKY JAMES M 5 14/06/2007 Y " MEERKAT" JOHN JONES M 9 15/12/2007 v v " LEOPPARD" JIM LEE M 8 16/12/2002

Replies are listed 'Best First'.
Re: perl array from csv file creating newline in unexpected place
by Corion (Patriarch) on Nov 20, 2015 at 06:55 UTC

    In @cvstemp and @arraytemp, you append the new lines always with a newline \n at the end. You most likely don't want that newline.

    I found this by searching your source code for \n because you mentioned "newlines".

    Also, you don't need to split and rejoin your data all the time. You should be looking into perldsc to find out how to store your spreadsheet as array of arrays or array of hashes.