Yesterday I wrote an SQL statement:
select sum(whatever) from -- 10 tables, omitted -- where -- whole pile of stuff omitted -- group by -- another pile of things
The idea being that I would plug in various placeholder values and get back the value I was interested in. This worked very well, and as I was pressed for time I simply derefenced the result of fetchrow_arrayref to get my value. The code looked something like:
$sth->execute($foo, $bar, $rat) or die $sth->errstr, $/; my $sum = $sth->fetchrow_arrayref->[0]; $sth->finish;
This worked perfectly well for quite some time until I hit a particular set of inputs which produced an empty result set. At that point, fetchrow_arrayref returned undef, and perl rightly got upset when I asked it to dereference it to obtain the first element.
So I sighed, cursed my haste and realised I had to copy the result into an intermediary to check whether it was defined:
$sth->execute($foo, $bar, $rat) or die $sth->errstr, $/; my $r = $sth->fetchrow_arrayref; my $sum = $r ? $r->[0] : 0; $sth->finish;
but before I did so, I had an insight that allowed me to zen the code:
$sth->execute($foo, $bar, $rat) or die $sth->errstr, $/; my $sum = ($sth->fetchrow_arrayref || [0])->[0]; $sth->finish;
That is, call the fetchrow_arrayref. If that evaluates to false, the expression lazily collapses to a single element array ref containing zero. And then dereference whatever happened, and take the first element.
And then I finished the program. I did leave a comment above the statement explaining what was going on. I like the idiom, but I worry that it's too clever for its own good.
Comments? Opinions?
• another intruder with the mooring in the heart of the Perl
In reply to Is this too clever? (or, stupid DBI tricks) by grinder
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |