$field = $sth->fetchrow_array();

As you say, the result is not documented. Some would say this is just a bug, like using length to get the length of an array.

Something sensible in this case could use wantarray, as in:

sub fetchrow_array { my @out; # ... if ( wantarray ) { # list return @out; } elsif ( ! defined wantarray ) { # void return; } elsif ( scalar @out <= 1 ) { # scalar return $out[0]; } else { # scalar die 'too many return values for scalar'; } }

That seems safe and yet still not quite satisfactory. I'm not sure I'd want to have some code that worked suddenly fail because one valid query (returning one field per record) changed to another valid query (returning many fields per record).

Given a "$scalar = x()", I expect that x() returns a scalar. I know very well that's not necessarily true

It is necessarily true. x() cannot return anything but a scalar in scalar context.

I should have said something like, "I know very well it might return more than one value in some other context." My point was that, seeing "$scalar = x()" implies to me that x() only returns one value, ever, in any context. I would ordinarily think that "@array = x()" would give me an array with one element. Using wantarray allows x() to violate that expectation, often for no good reason.

I think a case can be made for context-sensitivity in DBI::fetchrow_array, and probably lots of other places. I'll say again, however, I think those cases are still very rare.


In reply to Re^2: Use of wantarray Considered Harmful by kyle
in thread Use of wantarray Considered Harmful by kyle

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.