On Fri, Oct 19, 2001 at 10:36:38PM -0400, misc    wrote:
> now the following code:
> 
> $qry = "SELECT * FROM table WHERE field=5";
> $sth = $dbconn->prepare($qry);
> $sth->execute or die($sth->errstr);
> $row1 = $sth->fetchrow_hashref;
> $temp = $$row1{'field'};
> print " got here ** ";
> if ($row1 ne "") {
>  print "row not empty";
> } else {
>   print "row is empty";
> }    
> 
> with the same SQL statement and database
> prints out:
>  got here ** row not empty 
> 
> why?  why is the reference not undef still
> in the second case?  By dereferencing an
> undef reference it becomes defined?  Isn't
> that akin to raising the dead?  I am running activestate Perl 5.004 under win98se.  
>I am 
> using DBD::ADO and an access2000 database.
> 

This is autovivification.  See perlref:

           The left side of the arrow can be any expression
           returning a reference, including a previous
           dereference.  Note that $array[$x] is NOT the same
           thing as $array->[$x] here:
 
               $array[$x]->{"foo"}->[0] = "January";
 
           This is one of the cases we mentioned earlier in which
           references could spring into existence when in an
           lvalue context.  Before this statement, $array[$x] may
           have been undefined.  If so, it's automatically
           defined with a hash reference so that we can look up
           {"foo"} in it.  Likewise $array[$x]->{"foo"} will
           automatically get defined with an array reference so
           that we can look up [0] in it.  This process is called
           autovivification.


If you don't want to autovivify $row1, do this instead:

if ($row1) {
    $temp = $row1->{'field'};
}

Note that you can simply see if $row1 holds a true value, rather than
comparing it to the empty string.


Ronald

Reply via email to