Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

use of uninitialized values

by Baz (Friar)
on Apr 06, 2003 at 14:09 UTC ( #248435=perlquestion: print w/replies, xml ) Need Help??

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

I have the following in my script -
$coord_{$key1}{$key2}[[2]] = $sth->fetchrow_array;
where fetchrow_array belongs to DBI

Sometimes though fetchrow_array will not find an entry, so what I want to do is store missing entries in my database as 0 in the corresponding variable. So lets say the corresponding entry for $coord_{"AB"}{5}[[2]] has no entry in the database, then I want $coord_{"AB"}{5}[[2]] = 0 instead of $coord_{"AB"}{5}[[2]] = "uninitialized value";

So I could use something like -

if($coord_{$key1}{$key2}[2] eq "uninitialized value") { $coord_{$key1}{$key2}[2] = 0; }
but how does perl represent this "uninitialized value" that I'm using above? I hope that makes sense.

Thanks
Barry.

Replies are listed 'Best First'.
Re: use of uninitialized values
by nothingmuch (Priest) on Apr 06, 2003 at 14:13 UTC
    Perl has a function named undef, which either undefines a value (as in undef @bar), or returns an undefined value ($foo = undef). To check for definedness, you use the function defined:
    if(not defined($coord_{$key1}{$key2}[2])) {  $coord_{$key1}{$key2}[2] = 0; }
    or more simply
    $coord_{$key1}{$key2}[2] = 0 unless defined $coord_{$key1}{$key2}[2];
    or even better
    $coord_{$key1}{$key2}[2] ||= 0;
    Update:I forgot to say that undef is the 'uninitialized value' - an undefined (not only false but with no value).

    -nuffin
    zz zZ Z Z #!perl
Re: use of uninitialized values
by Anonymous Monk on Apr 06, 2003 at 14:13 UTC
    $coord_{$key1}{$key2}[2] ||= 0;
Re: use of uninitialized values
by graff (Chancellor) on Apr 07, 2003 at 01:08 UTC
    Assuming that you're using DBI to do SQL queries, you could have the SQL statement return something suitable in place of a null (empty) field value -- e.g.:
    select NVL(some_column,0) from some_table where some_condition...
    The "NVL( column, value )" expression in SQL (in oracle, at least) will yield "value" in the case where "column" is null.

      PostgreSQL and SQL Server use COALESCE. You can give COALESCE a list of values. It will return the first one that is not NULL.

      90% of every Perl application is already written.
      dragonchild

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://248435]
Approved by nothingmuch
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2021-05-15 18:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Perl 7 will be out ...





    Results (150 votes). Check out past polls.

    Notices?