Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: converting a csv file to fix width text

by flexvault (Monsignor)
on Oct 31, 2015 at 15:26 UTC ( [id://1146577] : note . print w/replies, xml ) Need Help??

in reply to converting a csv file to fix width text

Welcome jazzlover,

The answers you received so far are all excellent.

So this is my suggestion on making your life easier, if you are going to stay at the new job for some years to come.

Before Perl, I used fixed width files and/or csv files, so naturally I did the same with Perl. But once I learned and re-learned the power of the Perl hash, I now keep all data files as saved hashes. (Note: I started a simple sample, but it became too complex.) This is a skeleton using your data for an example (untested).

use strict; use warnings; our %people = (); # I use 'our' for global and 'my' for temporary da +ta our $ksep = "\r"; # you define your key separator our $dsep = "\t"; # you define your data separator # I use chr(30) & chr(254) respectfully! # Use something that will not be part # of the raw data or use 'pack' for the # length of the data elements. my $key = 'pat'; my $data = "$key$ksep"; $data .= "Name=$key$dsep"; # You can use "\t" instead of '=' $data .= "Address=50 car road$dsep"; $data .= "Postcode=aa1 1ab$dsep"; . . . $data .= "END=Finish"; # I like an end ( helps with 'split' ) $people{$key} = $data # key is also part of data # This can now to saved in a flat file or database or both. # You need a double 'split' to get the key and data # Then each data field needs to be split on '=' or "\t"
So why is this better?

The format of the data can be converted (subroutine?) to whatever format is needed. It's easy to add more data fields if needed.

Recently, I had to add 3 new fields for a report. No problem!

Each day I have audit reports that must be in Soap, XML, PDF, MIME, docx, etc. formats, but all the raw data is saved in key/value database as saved Perl hashes. Perl is G R E A T !


"Well done is better than well said." - Benjamin Franklin