open(OUT,">/path/to/file.txt") or die $!; for(my $i=$tape;$i<=$tape1;$i++){ # issue query $sth = $dbh->prepare("SELECT the_number,',',client_company_name,',',name,',',_Title,',',_Version,',',_PGM_Duration,',',_Tape_Format FROM tapes_2 WHERE the_number='$pref$i'"); $sth->execute (); my $output = $sth->fetchall_arrayref; my @output = @$output; if($output[0]){ print OUT <<"end_txt"; end_txt foreach my $row (@output){ print OUT $row->[0]; print OUT $row->[1]; print OUT $row->[2]; print OUT $row->[3]; print OUT $row->[4]; print OUT $row->[5]; print OUT $row->[6]; print OUT $row->[7]; print OUT $row->[8]; print OUT $row->[9]; print OUT $row->[10]; print OUT $row->[11]; print OUT $row->[12]; } chmod(0777,$file); # save tape number for later displaying push(@work_done, "$pref$i"); } } close(OUT);