# table_2_csv.pl # # Read a table (formatted similar to the one in the # DATA section) and reformat it into a CSV file. # # TODO: # 1) Make it actually open a file and process it, # instead of only looking at the DATA section. # 2) Maybe pull the file reading and column split # into a separate function to handle the extra # column 0 symptom. # use strict; use warnings; # Locate header: discard lines until we find # a line containing "-----" while () { last if /-----/; } # Gather the headings my @headings; while () { last if /=====/; my @fields = split /\s*%\s*/; for my $i (0 .. $#fields) { next if $fields[$i] =~ /----/; $headings[$i] .= $fields[$i]; } } print_as_csv(@headings); # Extract the data while () { last if /-----/; my @fields = split /\s*%\s*/; print_as_csv(@fields); } sub print_as_csv { my @data = @_; # Band-aid to handle our borders: first column # is always empty, so get rid of it shift @data; # Quote everything that's not a number (it *is* # supposed to be a CSV file!) for my $i (0 .. $#data) { if ($data[$i] =~ /[^-\+\.0-9]/) { # has non-numeric characters, so quote it $data[$i] = qq("$data[$i]"); } } print join(", ", @data), "\n"; } __DATA__ TEXT MATCHING header here! . . . snip: no reason to repeat the data . . .