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

Here is my code which gives me an output like this:

ABCcorp 246 Cerritos Ave Signal Hill CA 90755 562-427-555

#output database results while (@row=$sth->fetchrow_array) { print FINAL "@row\n" } close FINAL;

How do I code it so that it formats with a newline after each of the fields so that the data appears as a column?

Replies are listed 'Best First'.
Re: Array results
by davido (Cardinal) on Oct 29, 2004 at 00:50 UTC

    Try this if you want it all in a single column:

    { local $" = "\n"; while ( my @row = $sth->fetchrow_array ) { print FINAL "@row\n\n"; } }

    This will print each element in @row on its own line, and will print an extra blank line between each fetchrow_array iteration. I made use of the special variable $" in order to cause interpolated lists to have a \n newline placed between each element.

    If you don't like to use list interpolation within a quoted construct, you can also do it like this:

    { local $, = "\n"; while ( my @row = $sth->fetchrow_array ) { print FINAL @row, "\n"; } }

    This has the same output. You'll notice that this time I'm only explicitly printing \n once, but because it's another item in a list, it gets a \n inserted between it and the last element of @row. So again, with this method, each element of @row will be on its own line, and you'll get a blank line between records.

    And if you don't like playing with special variables, here's another approach:

    while ( my @row = $sth->fetchrow_array ) { print FINAL map( { $_ . "\n" } @row ), "\n"; }

    This time map is creating a new list to be printed, based on the elements of @row with a newline appended to each element. ...and of course that trailing newline is printed too, to put a blank line between records.


    Dave

      and don't forget good old join:

      while ( my @row = $sth->fetchrow_array ) { print FINAL join("\n", @row), "\n"; }

        print FINAL join("\n", @row), "\n";

        print FINAL join( "\n", @row, "" ); # does the same, looks smart ;)

        Cheerio, Sören