use strict; use warnings; # <-- always use strict *and* warnings use Spreadsheet::WriteExcel; use Text::CSV_XS; # Check for valid number of arguments <-- @ARGV in scalar context gives the number of entries in the list @ARGV == 2 or die "Usage: csv2xls csvfile.txt newfile.xls\n"; # Open the Comma Separated Variable file open my $fh, "<", $ARGV[0] or die "$ARGV[0]: $!"; # <-- use lexical file handles and 3-arg open # Create a new Excel workbook my $workbook = Spreadsheet::WriteExcel->new ($ARGV[1]); my $worksheet = $workbook->add_worksheet (); # Create a new CSV parsing object my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 }); # <--- use diagnostics and binary # Row and column are zero indexed my $row = 0; while (my $row = $csv->getline ($fh)) { # <-- safe and fast parsing # due to auto_diag there is no reason for error-checking my $col = 0; $worksheet->write ($row, $col++, $_) for @{$r}; $row++; }