Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

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'

Replies are listed 'Best First'.
Re: Printing the header row
by martin (Friar) 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://993347]
Approved by kcott
Front-paged by Arunbear
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2018-05-23 23:40 GMT
Find Nodes?
    Voting Booth?