Tech_20
asked on
Perl script not writing to .csv file
I have a Perl script written to extract the 3rd column out of a beginning .csv file and then to place that content into a new .csv file. I used the proper modules and believe I am using the correct syntax since there are no errors but there is no content written into the new .csv file. Please refer to the attached text file. Thanks.
textCSV.txt
textCSV.txt
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Text::CSV;
use Text::CSV_XS;
my $file = $ARGV[0] or die "Need to get CSV file on the command line\n";
open (my $data, "<", $file) or die "Could not open '$file' $!\n";
my $csv = Text::CSV->new ({
binary => 1,
auto_diag => 1,
});
while (my $fields = $csv->getline ($data)) {
$fields->[2] =~ m/.+/ or next;
push (my @fields, $fields);
}
close $data;
# print the array to screen to see that there is something in it.
print "@$fields\n";
# print the array to output file.
open $data, ">", "new.csv" or die "new.csv: $!";
print $data join ("\n", map {$_} @fields);
close $data;
use strict;
use warnings;
use feature 'say';
use Text::CSV;
use Text::CSV_XS;
my $file = $ARGV[0] or die "Need to get CSV file on the command line\n";
open (my $data, "<", $file) or die "Could not open '$file' $!\n";
my $csv = Text::CSV->new ({
binary => 1,
auto_diag => 1,
});
while (my $fields = $csv->getline ($data)) {
$fields->[2] =~ m/.+/ or next;
push (my @fields, $fields);
}
close $data;
# print the array to screen to see that there is something in it.
print "@$fields\n";
# print the array to output file.
open $data, ">", "new.csv" or die "new.csv: $!";
print $data join ("\n", map {$_} @fields);
close $data;
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
@ozo; @fishmonger: Thanks. Again, I'm trying to extract the 3rd column out of a beginning .csv file and then to place that content (only) into a new .csv file. Both scripts work except it produces the exact same content in all columns.
@mikelfritz: Thanks. However, this script produces the errors...
Global symbol "$fields" requires explicit package name at CSM_data_2.plx line 21.
Global symbol "@fields" requires explicit package name at CSM_data_2.plx line 25.
Execution of CSM_data_2.plx aborted due to compilation errors.
I think we're close, just need the 3rd column only.
@mikelfritz: Thanks. However, this script produces the errors...
Global symbol "$fields" requires explicit package name at CSM_data_2.plx line 21.
Global symbol "@fields" requires explicit package name at CSM_data_2.plx line 25.
Execution of CSM_data_2.plx aborted due to compilation errors.
I think we're close, just need the 3rd column only.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
@FishMonger: That worked. Thanks.
You probably want them to be the same array
Open in new window