Rocko19 has asked for the wisdom of the Perl Monks concerning the following question:


Hi
I want to print certain values in the header before I write data to the CSV files. All the records are written into the file correctly but the header is not spliting up in each columns as it shud be
Please help.

Rocko

Replies are listed 'Best First'.
Re: How to print header to a CSV file
by Corion (Patriarch) on Sep 07, 2009 at 12:11 UTC

    If you just want to generate output from SQL queries, I recommend using Querylet instead.

    But for the problem at hand, maybe you want to use the join function so you don't miss spaces at parts of your header sequence?

    Your program, when reduced to the relevant parts looks like this:

    $header_rec .= "NAME "; $header_rec .= "ID "; $header_rec .= "REGION "; $header_rec .= "UNIT"; $header_rec .= "STATUS "; print "[$header_rec]\n";

    If I change it to the below, it works for me as expected:

    my @columns = ('NAME','ID','REGION','UNIT','STATUS'); print join( "\x09", @columns), "\n"; # or alternatively print "[@columns]\n";

    Also, you'll be well-advised to use a tab character (\0x09) instead of a blank to separate your output.

Re: How to print header to a CSV file
by Perlbotics (Archbishop) on Sep 07, 2009 at 12:19 UTC

    You forgot to separate the items of the header-record, e.g. try:

    $header_rec = join(',', qw(NAME ID REGION UNIT STATUS));
    Furthermore, you should open (give the thee argument version a try) and close the file only once - before writing the header and after writing the last line of data. Otherwise, your program will be slower than necessary. Then, you probably want to use '>' instead of '>>' since the latter appends to an existing file.

    The other obligatory hint is Text::CSV since re-inventing CSV processing is not worth the pain (unless it is for educational purpose, I guess).

Re: How to print header to a CSV file
by CountZero (Bishop) on Sep 08, 2009 at 06:18 UTC
    Do not re-invent wheels which were already invented by others and work very well: Text::CSV has all you need (and more).

    Also, why are you repeatedly opening and closing your output file? It will slow down your program enormously.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James