How to get csv outfile to print out each row on a separate line

I have the script to extract rows and output to a csv file. But, the file is appending each row to resulting in a concatenated output.
I want to output each row to a single line (see present and expected output below)

use strict;
use warnings;
use DBI;
use Date::Manip;
use Getopt::Std;

Date_Init('TZ=US/Central','Internal=1');

$| = 1;

my %opts;
getopts('d', \%opts);

my $date    = UnixDate(($opts{'d'} || 'today'), '%q');
my $nodata = 0;
my ($db, $user, $pw, $wkdir, $firstday, $lastday)  = @ARGV;

#Check to see if required parameters are received by appworx

unless($db && $user && $pw && $wkdir && $firstday && $lastday) 
{
	print("args = $date, $db, $user, $pw, $wkdir, $firstday, $lastday\n\n");
    die("\n\n  - ERROR:  The Required number of arguments were not received.  Verify that the AppWorx prompts are correct and reset the module..\n\n");
} 

# Display parameter values passed by the appworx

print("\n");
print("Database Instance  : $db \n\n");
print("Connected as User  :	$user \n\n");
print("Output Directory is : $wkdir \n\n");

# Connectivity check to the database else display failed connectivity

my $dbh = DBI->connect("dbi:Oracle:$db", $user, $pw) or die("Cannot connect to Database '$db' " . DBI->errstr());

# Capture counts for distinct partitions for given firstday and lastday dates
my $sthcounts = $dbh->prepare(qq(select /*+ full(r) parallel(r,4) */ count(distinct r.partition_key) from region r where r.status = 'N' and r.firstday = to_date(?,'YYYYMMDD') and r.lastday = to_date(?,'YYYYMMDD')));

# Prepare statement gets the partition key from the function get_rec_partition_key inside the rbl_dagg_common package
# Values of partition key will be passed on by appworx will be parameterized in the script

$sthcounts -> bind_param(1,$firstday);
$sthcounts -> bind_param(2,$lastday);
$sthcounts -> execute();

# Get value of rowcount returned from Count of partition keys from rp_rec_gen_extract table
my $rowcount = ($sthcounts-> fetchrow_array())[0];

# Check if single partition exists for a given firstday/lastday parameters, ROW COUNT RETURNED will be 1 and then proceed with extract out columns from the table to a csv file
# IF multiple partition exists for a given firstday/last day set - then PROCESS TO ABORT
if ($rowcount gt 1)
{ 
  die ("ERROR: MORE THAN 1 PARTITION EXISTS FOR GIVEN FIRSTDAY LASTDAY SET OF DATES - PROCESS ABORTED!!!\n");
}
else
{
my $sth = $dbh->prepare(qq(select /*+ full(r) parallel(r,4) */  distinct r.partition_key from region r 	where r.status = 'N' and r.firstday = to_date(?,'YYYYMMDD') and r.lastday = to_date(?,'YYYYMMDD')));

 # Display parameter value of First Day from appworx
 print("First Day parameter passed from appworx : $firstday \n\n");

 # Display parameter value of Last Day from appworx 
  print("Last Day parameter passed from appworx : $lastday \n\n");
  
$sth->execute($firstday, $lastday);
my ($dataextract) = $sth->fetchrow_array;
$sth->finish;

my $ref_dataextract = join '', "'",$dataextract ,"'";

#Assign variable to the partition key and use this variable in subsequent prepare statements and to extract columns to outfile
my $genextract = $dbh->prepare(qq(SELECT TO_CHAR(STARTTIME,'MM/DD/YYYY') TRADEDATE, DSNUMBER, SITENAME, PGNAME
												FROM region WHERE PARTITION_KEY = $ref_dataextract))
   						or die("Could not get data from table '$_'".DBI->errstr);
   						
$genextract->execute();
														              										
my @allrows;
my @columns;
my $getfilename = join '', $firstday ,'_',$lastday,'.csv'; 
my $rc  = $genextract->fetchrow_hashref() or $nodata = 1;   
         my @row = @{$genextract ->{NAME}};
         foreach my $col (@row)
         {
            my $name = $col;
            $name =~ s/\s+//g;
            my $data = $rc->{$name};                   
            push @allrows, $data;
            push @columns, $name;       
        }  
my $dumpdir = "$wkdir/RECgen_$getfilename";  
    
open (OUT, ">$dumpdir") or die(" - Could not open $dumpdir for export. $!");
       
#  List out all the columns/rows with header information and generating a csv outfile..
			$" = ",";
      print OUT "@columns\n";
      print OUT "@allrows\n";
       
      while (my $row = $genextract->fetchrow_hashref()) 
      {
            foreach my $col (@columns)
            {                       
               print OUT $$row{$col},","; 
            }
      }    
     close(OUT);

# Disconnect from the database and export out the files    
# File output process completion Notification

print "The RECgen_$getfilename file is generated to output directory..\n";

Open in new window


Present Output
TRADEDATE,DSNUMBER, SITENAME,PGNAME
07/02/2014, 0152039723000,                            DG_RDLML,NYSTC,07/03/2014,0152039723000,DG_RDLML,nystdc,07/18/2014,0152039723000,DG_RDLML,CHGNC,08/02/2014,0101010011,DSTCTS,DFW

Expected Output
TRADEDATE,DSNUMBER, SITENAME,PGNAME
07/02/2014,0152039723000, DG_RDLML,NYSTC
07/03/2014,0152039723000,DG_RDLML,nystdc
07/18/2014,0152039723000,DG_RDLML,CHGNC
08/02/2014,0101010011,DSTCTS,DFW

Open in new window

steve2312Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

wilcoxonCommented:
Before line 107, add this line and everything should work:
print OUT "\n";

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
steve2312Author Commented:
Thanks wilcoxon :)  That worked!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Perl

From novice to tech pro — start learning today.