Evaluating equality in perl using elements taken from an array ref
I have a small perl script that needs to evaluate the equality of two parameters and a small return from the database.
my ($firstId, $secondId, $firstReturnedId, $secondReturnedId, $picCount);
my $pics = $dbh->prepare(qq[select id from pictures limit 10]);
$firstId = q->param('firstId');
$secondId = q->param('secondId');
$pics->execute or die;
my $picids = $pics->fetchall_arrayref;
$picCount = scalar(@{$picids});
$firstReturnedId = $picCount > 0 ? shift(@{$picids}) : 0;
$secondReturnedId = $picCount > 1 ? pop(@{$picids}) : $firstReturnedId;
Here, a quick look at my debugger shows that $picCount = 1 and $firstReturnedId = 9020 and $secondReturnedId = 9020. However, they are both denoted as
ARRAY(0x9e79184)
0 9020
in the debugg开发者_C百科er so when I perform the final check
my $result = (($firstId == $firstReturnedId) && ($secondId == $secondReturnedId)) ? 1 : 0;
I get $result = 0, which is not what I want.
What am I doing wrong?
DBI::fetchall_arrayref
returns a reference to a list of "row results". But since there could be more than one value in a row result (e.g., your query could have been select id,other_field from pictures
), each row result is also a reference to a list. This means you have one more dereferencing to do in order to get the result you want. Try:
$picCount = scalar(@{$picids});
if ($picCount > 0) {
my $result = shift @{$picids};
$firstReturnedId = $result->[0];
} else {
$firstReturnedId = 0;
}
if ($picCount > 1) {
my $result = pop @{$picids};
$secondReturnedId = $result->[0];
} else {
$secondReturnedId = $firstReturnedId;
}
or if you still want to use a concise style:
$firstReturnedId = $picCount > 0 ? shift(@{$picids})->[0] : 0;
$secondReturnedId = $picCount > 1 ? pop(@{$picids})->[0] : $firstReturnedId;
精彩评论