http://www.perlmonks.org?node_id=726071


in reply to Re^2: selectrow_array() confusion
in thread selectrow_array() confusion

I really have shown you the right code, honestly.

This is a minimum test case

#!/sw/bin/perl use strict; use warnings; use DBI; my $d = DBI->connect( 'DBI:mysql:imagedb:localhost', 'root', '******', { RaiseError => 1 } ) || die("couldn't connect to database"); my ( $min, $max ) = $d->selectrow_array( "SELECT min(id),max(id) from images where gallery_path like '/px6% +'") || die $d->errstr; print "min: $min; max: $max;\n";
And when I run it, I get:
Use of uninitialized value in concatenation (.) or string at ab.cgi li +ne 13. min: 61893; max: ;


Nobody says perl looks like line-noise any more
kids today don't know what line-noise IS ...

Replies are listed 'Best First'.
Re^4: selectrow_array() confusion (or vs ||)
by MidLifeXis (Monsignor) on Nov 26, 2008 at 14:01 UTC
    "SELECT min(id),max(id) from images where gallery_path like '/px6%' +") || die $d->errstr;

    should be

    "SELECT min(id),max(id) from images where gallery_path like '/px6%' +") or die $d->errstr;

    You are forcing the selectrow_array call to be in scalar context by use of the "c-style logical or" || (see the precedence chart in perlop). You need to use or. Quoth the docs:

    If called in a scalar context for a statement handle that has more than one column, it is undefined whether the driver will return the value of the first column or the last. So don't do that. Also, in a scalar context, an "undef" is returned if there are no more rows or if an error occurred. That "undef" can't be distinguished from an "undef" returned because the first field value was NULL. For these reasons you should exercise some caution if you use "selectrow_array" in a scalar context, or just don't do that.

    The meme for spewing errors with a postfix or die uses "or" for a reason. It binds lower than all other operations, so it will be executed only if the entire statement itself fails (well, almost).

    You have this error in the line above as well. I would also change your connect call to use the or meme instead of the || one.

    As a learning device for others: this is a reason to include a complete working example of the failing code. Many (if not most) of the responses above were focusing on DBI/DBD, when in reality the problem was internal to perl operator misuse. That was not discovered until a complete code example was posted that exhibited the behavior.

    and just so this gets picked up as an example when searching:

    • or vs ||

    --MidLifeXis

      Thank you!

      I now have a lot of code to check through...



      Nobody says perl looks like line-noise any more
      kids today don't know what line-noise IS ...