I have two scripts in which I'm experimenting with CSV_XS. In the first, I hard-coded everything: source directory, filename, and the csv delimiter I wanted to look for. The script works great. In the second, however, I try to dynamically discover as much as possible. That script seems to run, but it outputs nothing.
I'm having trouble figuring out why, and I was hoping you fine Perl folks wouldn't mind lending a second set of eyes to the problem:
First, the successful script:
#!/usr/bin/perl -w
use Text::CSV_XS;
my @records;
my $file = 'Data/space.txt';
my $csv=Text::CSV_XS->new({ sep_char => " " });
open(FILE,$file) || die "Couldn't open $file: $!\n";
while (<FILE>){
$csv->parse($_);
push(@records,[$csv->fields]);
}
close FILE;
foreach (@records){
print $_->[0], ",", $_->[1], ",", $_->[2], ",", $_->[3], ",", $_->[4], "\n";
}
And second, the "failing" script:
#!/usr/bin/perl -w
use Text::CSV_XS;
$input_dir = $ARGV[0]; #I pass "Data" on the command line
my @records;
opendir(DIR, $input_dir) || die "cannot open dir $input_dir: $!";
my @filelist = grep {$_ ne '.' && $_ ne '..'} readdir DIR;
closedir DIR;
foreach $file (@filelist){
print "Input file='",$input_dir,"/",$file,"'\n";
if ($file =~ /comma/) {$sep=','}
elsif ($file =~ /pipe/) {$sep='|'}
elsif ($file =~ /space/) {$sep=' '}
else {die "Cannot identify separator in $file: $!";}
print "Delimiter='",$sep,"'\n";
open(FILE,$input_dir||"/"||$file) || die "Couldn't open $file: $!\n";
my $csv=Text::CSV_XS->new({ sep_char => $sep });
while (<FILE>){
$csv->parse( $_ );
push(@records,[$csv->fields]);
print "File Input Line:'", $_ ,$csv->fields,"'\n";
};
close FILE;
}
foreach $record (@records){
print $record->[0], ",", $record->[1], ",", $record->[2], ",", $record->[3], ",", $record->[4], "\n";
}