in reply to converting txt to csv and formatting
G'day csorrentini,
"This is what I currently have as far as reading in the text file and writing the csv file."
I concur with earlier comments regarding the use of Text::CSV.
"My problem is I have no idea how I would go about grabbing data into specific fields with the way the txt file is currently formatted."
I would probably just read the lines in groups of three. Here's my take on what (the guts of) your code might look like:
#!/usr/bin/env perl -l use strict; use warnings; use autodie; use constant INFO_LINES => 3; use Text::CSV; my $txt_in = 'pm_1092407_txt_in.txt'; my $csv_out = 'pm_1092407_csv_out.csv'; cat_file($txt_in, 'INPUT'); my $csv = Text::CSV::->new; open my $txt_in_fh, '<', $txt_in; open my $csv_out_fh, '>', $csv_out; my @captures; while (<$txt_in_fh>) { chomp; push @captures, $_; unless ($. % INFO_LINES) { $csv->print($csv_out_fh, [@captures]); @captures = (); } } close $txt_in_fh; close $csv_out_fh; cat_file($csv_out, 'OUTPUT'); sub cat_file { my ($file, $prompt) = @_; $prompt = 'FILE' unless defined $prompt; print '=' x 64; print "$prompt ($file):"; print '-' x 64; system cat => $file; }
Output:
================================================================ INPUT (pm_1092407_txt_in.txt): ---------------------------------------------------------------- Jacobs, April 750.467.9582 quam.quis@sedhendrerit.org Mays, Martena 870.348.1974 sollicitudin@nonummyFusce.org McNeil, Brennan 289.527.6151 lobortis@nisl.com Sexton, Melvin 599.927.5337 in.felis@varius.com Blackburn, Prescott 661.589.1228 sed@egetlaoreetposuere.edu ================================================================ OUTPUT (pm_1092407_csv_out.csv): ---------------------------------------------------------------- "Jacobs, April",750.467.9582,quam.quis@sedhendrerit.org "Mays, Martena",870.348.1974,sollicitudin@nonummyFusce.org "McNeil, Brennan",289.527.6151,lobortis@nisl.com "Sexton, Melvin",599.927.5337,in.felis@varius.com "Blackburn, Prescott",661.589.1228,sed@egetlaoreetposuere.edu
-- Ken
|
|---|