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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.