Link to home
Start Free TrialLog in
Avatar of Tech_20
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
Avatar of ozo
ozo
Flag of United States of America image

Your two @fields arrays are separate local declarations
You probably want them to be the same array
#!/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";
my @fields;
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 (@fields, $fields);
}
close $data;

open $data, ">", "new.csv" or die "new.csv: $!";
$csv->say ($data, $_) for @fields;
close $data or die "new.csv: $!";

Open in new window

#!/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;
SOLUTION
Avatar of FishMonger
FishMonger
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tech_20
Tech_20

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.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tech_20

ASKER

@FishMonger: That worked. Thanks.