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

Dear monks

I was hoping you would be able to help me understand the following error handling code

my $rows_deleted = $dbh->do(q{ DELETE FROM table WHERE status = ? }, undef, 'DONE') or die $dbh->errstr;
I believe that dbh->do will retrun undef if there is an error, but what is the result of assiging an undef to a varible? I guess it must be false otherwise the or test would be passed and the die statement wouldn't happen? I thought an assignment was always true

many thanks

Replies are listed 'Best First'.
Re: understanding this database error code handling
by Corion (Patriarch) on Dec 10, 2010 at 22:52 UTC

    No.

    An assignment always has the assigned value also as its return value. You can easily check that by printing the value of an assignment:

    print $foo = '0'; print $foo = 'bar';
Re: understanding this database error code handling
by 7stud (Deacon) on Dec 11, 2010 at 00:46 UTC

    "Programming Perl 3rd" states it a little differently:

    Regardless of which kind of assignment operator you use, the final value of the variable on the left is returned as the value of the assignment as a whole.

    So you can look at it like this:

    my $result = 'hello'; $result or die "I'm dead"; $result = undef; $result or die "I'm dead down here."; --output:-- I'm dead down here. at line 5.

    The fact that a value is returned by the assignment operator let's you do this:

    my ($x, $y, $z); $x = $y = $z = 20; print "$x $y $z"; --output:-- 20 20 20

    The rightmost assignment executes first.

      7stud (++) is technically correct and the quote cited is worth noting, but beware:
      Your mileage will vary if you use warnings; if you make lines 2 and 5 into print lines, and even if you attempt to run ("test") lines 4 and 5 as a one-liner.

      The last is merely cosmetic;

      >perl -e "$result = undef; $result or die 'I am dead down here.';" I am dead down here. at -e line 1.

      but the other two variants invoke (or illustrate) something quite different than that about which OP appears to have asked.

Re: understanding this database error code handling
by wagnerc (Sexton) on Dec 11, 2010 at 00:38 UTC
    if the dbh->do doesn't return something "true" then the die() will execute. 0, undef, and blank are all false results and would make it die. The assignment is "true" but the variable in its post assignment form is the final thing evaluated. So whatever the variable content is is what the final statement value is. This is because an assignment will always succeed, so there's no point in checking it.