http://qs1969.pair.com?node_id=347523


in reply to On Scalar Context

After reading flyingmoose's reaction to merlyn's post, I wandered through the POD myself to see if any of the behaviors that merlyn discussed are in some way undocumented such that they should come as a surprise. In just about every case, I found what I was looking for. I thought I might as well offer a little more detail on the ones that seemed most interesting.

Regarding flyingmoose's dismay over the situation, and his call for improved consistancy, this came up awhile back in What should be returned in scalar context?. I think that the general consensus was that functions should return what it makes sense for them to return in scalar context. In other words, don't get too caught up in trying to make all list-oriented functions return the same thing in scalar context. Not every shoe fits every foot.

To call these behaviors bugs is irrational, since they, in most cases, are doing something useful, and something that's defined in the documentation. The suggestion to not make assumptions is spot-on; that's why the POD is there -- so assumptions don't have to be made.


Dave

Replies are listed 'Best First'.
Re: Re: On Scalar Context
by fletcher_the_dog (Friar) on Apr 23, 2004 at 15:40 UTC
    I agree with davido, I don't think it makes sense to necessarily return the same thing every time in scalar context. It wouldn't make sense to have the "wantarray" function at all if scalar context always returned the length of the list. A sub-routine could just always return a list and if it was in scalar context the list length would be given. But the usefullness of "wantarray" is that you can return something different if you know you are in scalar context and not list context.
      From a evil-software design overlord perspective, I don't believe in wantarray being a good idea at all -- but you are probably glad that I'm not in charge. Technically, a function could do something entirely different based on context, not just in return type, and should it really be able to do that...

      Perl says do whatever you want, but in the general case, that's asking for trouble. Feel free to disagree, that's fine, but there are many aspects about Perl that make it sloppy. Sometimes these are the same reasons that make it flexible and cool, but sometimes not.

      So if people can argue Perl OO is ugly (most would agree), I can argue that wantarray is ugly... Never mind that wantarray seems to imply a true/false value from a design standpoint but actually returns undef, true, or false -- it's a three way statement.

Re: Re: On Scalar Context
by ambrus (Abbot) on Apr 24, 2004 at 21:15 UTC

    The perlfunc pod does define the return value of the 4-arg-select:

    Most systems do not bother to return anything use- ful in $timeleft, so calling select() in scalar context just returns $nfound.

    This is from the perlfunc manpage of perl 5.8.1.