tags:

views:

1005

answers:

4

I am running a query 'describe table' and it returns value of 'null' for the 'default' column. However, when I try to print the value from database to an HTML table it is not printing 'null'. It is just always blank.

This is how I am storing the data from database:

@nulls = ();

while (($null) = $sth1->fetchrow_array)
    {
    push (@nulls, $null);
    }

When I print the contents of array @nulls it never prints the literal value of 'null'. It is always blank. Is there a way to overcome this problem?

+2  A: 

I don't do Perl, but in every other language I've used, you have to test the value for null. If it is null, print out the string literal "null".

HardCode
Not a Perl guy either but in the languages I've used the 'null' from the database is not the same as the 'null' in the language. So care should be taken to test for the database 'null' value and not the language 'null' value.
Jonathon Watney
DBI does consistently map between the database null value and Perl's undef value.
ysth
+7  A: 

From http://search.cpan.org/~timb/DBI-1.607/DBI.pm , it will return null values as 'undef'.

Chris J
+10  A: 

As Chris J said, the null values are returned as undefined values.

If you had warnings enabled, you would have received an "undefined value in print" warning when you printed the values. Using the strict and warnings pragmata can save a lot of time debugging. The diagnostics pragma adds additional explanatory text to the standard warnings and fatal errors.

It's pretty easy to trap and replace the NULL values as they come from the database:

use strict;
use warnings;

my @nulls = ();
while ((my $null) = $sth1->fetchrow_array)
    {
            # before perl 5.10: use the ternary operator.
            push @nulls, defined $null ? $null : 'NULL';

            # perl 5.10 adds the defined-or operator: //
            push @nulls, $null // 'NULL';
    }

Or you could build your @nulls array the same way you show above, and then alter the nulls at display time.

my @pre_5_10  = map { defined $_ ? $_ : 'NULL' } @nulls;
my @perl_5_10 = map { $_ // 'NULL' } @nulls;
daotoad
+1  A: 

You don't say what database you're using, but you can do it at the SQL level if you don't mind a non-portable solution, e.g., in Oracle:

select NVL(some_column, 'NULL')
from some_table
runrig