in reply to Please help me with this ASCII file parsing assignment
use strict; use warnings; use Data::Dumper; use Text::CSV_XS; my $csv = Text::CSV_XS->new(); # create a new object while (<DATA>) { my $status = $csv->parse($_); # parse a CSV string into fields my @columns = $csv->fields(); # get the parsed fields print Dumper(\@columns); } __DATA__ aa,bb,cc 0,2,3
which prints:
$VAR1 = [ 'aa', 'bb', 'cc' ]; $VAR1 = [ '0', '2', '3' ];
Then, you could use the column positions to format your ASCII data file, by reading in the data line by line and adding commas as follows:
use strict; use warnings; my @cols = qw (5 11); while (<DATA>) { chomp; my $row = ''; my $start = 0; for my $cs (@cols) { my $offset = $start; my $length = $cs-$start; $row .= substr($_, $offset, $length) . ','; $start = $cs; } $row .= substr($_, $start); print "$row\n"; } __DATA__ 12345678901234567890 abcdefghijklmnopqrst
this prints:
12345,678901,234567890 abcde,fghijk,lmnopqrst
Perhaps you could adapt these simple examples for your application.
|
|---|