The following snippet of code is generating correct result files, but I would like to be able to control the order of the fields in the report. My preference would be that the fields be listed in the report in the same order as they are named in the table (or query) that the DBI statement handle is operating on.

I understand that hashes are unordered. But surely someone has devised a simple and elegant way to address this issue before I grappled with it. Any ideas out there?

-- Hugh

my $j = 0; my($line,$field,$record); RECORD: while ($record = $sth->fetchrow_hashref){ $line = ''; if($j == 0){ foreach $field (keys %$record){ $line .= $field . "\t"; } print RESULTS $line,"\n"; $j++; next RECORD; } $j++; foreach $field (keys %$record) { if (!defined($record->{$field})) { $record->{field} = ''; } else { $record->{$field} =~ s/\t/ /g; $record->{$field} =~ s/\r//g; if (/\n/) { $record->{$field} = s/(\s)\n/$1/g; $record->{$field} = s/\n(\s)/$1/g; $record->{$field} = s/\n$//; $record->{$field} = s/\n/ /g; } } $line .= $record->{$field} . "\t"; } print RESULTS $line,"\n"; } close(RESULTS);
UPDATE:

bobf:

You're the man!

That is exactly what I was looking for. And here is the patch which did the trick. Of course I had to apply it in two places, to the loop which created the header of field names, as well as to the loop which constructed each record in the report.

- foreach $field (keys %$record){ + foreach $field (@{$sth->{NAME}}) {
Now everything appears in the order defined by the query, even if I just grab a SELECT * FROM table; and the order is given by the organization of the table queried. Thanks again.

if( $lal && $lol ) { $life++; }

In reply to Controlling order of fields in report by hesco

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.