Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print CSV header with Tie::Handle::CSV

Tags:

perl

I wrote a perl script using Tie::Handle::CSV to process a bunch of data in a csv file and print out only what I need into a new csv file. Right now, I print out the header line with all of the field names by just a hardcoding it in like so:

print '"TERM", "STUDENT ID", "NAME", ..."'."\n";

I suspect this is a dumb way of doing this, but I don't know how to get access to the header from within the Tie::Handle::CSV object. It's instantiated like so,

my $fh = Tie::Handle::CSV->new($file,header=> 1);

and data is accessed like so,

$line -> {'CATALOG_NBR'}

I know enough to know this is a hash-reference, but not enough to know how to print the header using this rather than hardcoding it. Obviously, "they" usually change the precise column names and ordering just after I get the script working again each term.

Thanks a lot for any help! JA

like image 762
Jason Avatar asked Jan 13 '10 18:01

Jason


People also ask

Can CSV files have headers?

CSV and spreadsheet content rules. Each row in the file must contain the same number of cells. This rule also applies to the header row. The first row must contain column headers.

What is a CSV header?

A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. Initially, the CSV file is converted to a data frame and then a header is added to the data frame. The contents of the data frame are again stored back into the CSV file.


1 Answers

A bit late to the party, but I just released a new version of Tie::Handle::CSV (should be up on CPAN in a few hours). It adds support for a header() method, which returns a CSV formatted header. Usage might look like:

   my $fh = Tie::Handle::CSV->new( $file, header => 1 );
   print $fh->header;

Hope this helps,

  • danboo
like image 94
danboo Avatar answered Dec 09 '22 13:12

danboo