$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
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |