Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Printing the header row

by tobyink (Abbot)
on Sep 13, 2012 at 02:15 UTC ( #993347=CUFP: print w/ replies, xml ) Need Help??

It's quite common when outputting tabular data (be it CSV, or an HTML table) to ensure that column headers are printed once by using something along the lines of:

sub arrayref_to_csvline { ... } my $headers; while (my $row = $iter->()) { unless ($headers) { print arrayref_to_csvline($row->fields); $headers = 1; } print arrayref_to_csvline($row->values); }

I recently discovered a pattern that takes advantage of the return value of print (it returns 1 on success)...

sub arrayref_to_csvline { ... } my $headers; while (my $row = $iter->()) { $headers ||= print arrayref_to_csvline($row->fields); print arrayref_to_csvline($row->values); }

... just thought I'd share.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Comment on Printing the header row
Select or Download Code
Re: Printing the header row
by martin (Pilgrim) on Sep 13, 2012 at 15:48 UTC

    I guess the situation that the first round of an iteration provides information that is valid for all rounds, while not available before the iteration has started, is too unlikely to call for a general pattern.

    That said, a way to achieve the same result with slightly prettier code alignment could be:

    sub arrayref_to_csvline { ... } my $rows = 0; while (my $row = $iter->()) { print arrayref_to_csvline($row->fields) unless $rows++; print arrayref_to_csvline($row->values); }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://993347]
Approved by kcott
Front-paged by Arunbear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2014-09-22 07:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (182 votes), past polls