grinder has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Is this too clever? (or, stupid DBI tricks)
by kyle (Abbot) on Jan 05, 2008 at 15:14 UTC | |
|
Re: Is this too clever? (or, stupid DBI tricks)
by bradcathey (Prior) on Jan 05, 2008 at 15:40 UTC | |
|
Re: Is this too clever? (or, stupid DBI tricks)
by perrin (Chancellor) on Jan 05, 2008 at 16:25 UTC | |
|
Re: Is this too clever? (or, stupid DBI tricks)
by Jenda (Abbot) on Jan 05, 2008 at 16:56 UTC | |
by dsheroh (Monsignor) on Jan 05, 2008 at 18:06 UTC | |
by Jenda (Abbot) on Jan 05, 2008 at 19:38 UTC | |
|
Re: Is this too clever? (or, stupid DBI tricks)
by jplindstrom (Monsignor) on Jan 05, 2008 at 18:05 UTC | |
|
Re: Is this too clever? (or, stupid DBI tricks)
by Tux (Canon) on Jan 06, 2008 at 09:15 UTC |