Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

printing spaces in place of null values

Status
Not open for further replies.
Dec 17, 2002
41
US
First off, my name says it all. I am a perl tard, so please bear with any stupid questions I may have.

I am trying to get the perl to spit out the contents of my database, comma seperated for backup purposes. Below is what I have. At the moment it spits out the data the way I want except for one problem, when the perl hits an empty field it stops and goes to the next row. I need perl to see the empty field and substitute an empty space in for the field so when I repopulate the database, it fills that field. Any help would be greatly appreciated.

#Create the SQL.

my $sql = qq{SELECT * FROM THIS_TABLE };

#Prepare the SQL and execute.

my $sth = $dbh->prepare( $sql );
$sth->execute();

#Fetch output rows into array, plus prepare a
#print formatter for the results.

while ( my(@thisString) = $sth->fetchrow_array) {

#Print out the result

my $x=0;

my $data="data.txt";

open(DAT,">>$data") || die("Cannot Open File");
printf DAT &quot;$thisString[$x-1]%s&quot;, $x<=$#thisString ? &quot;, &quot;: &quot;\n\n&quot; while $thisString[$x++];
close(DAT);

}
$dbh->disconnect(); #Disconnect

 
Your printing drops out of the while loop because an empty field is evaluated as false in the while test. Using a method that doesn't depend on the value of the data would work better. An example
Code:
while ( my(@thisString) = $sth->fetchrow_array) {

    #Print out the result
    my $data=&quot;data.txt&quot;;
    open(DAT,&quot;>>$data&quot;) || die(&quot;Cannot Open File&quot;);
    print DAT join ', ', @thisString;
    print DAT &quot;\n\n&quot;;
    close(DAT);
    
}
jaa
 
A few things:

1) Shouldn't $x be initialized to 1, not 0, so the expression

$x - 1

starts off at 0?

2) You can store the contents of

$thisString[$x - 1]

in another variable, and check if this variable is null. If so, then set it to an empty space and then write out the variable to your file.

3) Why do you have open() and close() function calls within the outer while loop? I don't see any need to open and close the file more than once. Just a thought.
 
thanks for the help guys, it not only worked but it cleaned up my code quite a bit. much appreciated
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top