Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • First of all, I use 'return sort ...' in my code on a regular bases. I don't consider this a bug. If I write a function that's supposed to return a (sorted) list, and someone calls the function in scalar context, then it's the calling code that's buggy, not the subroutine. If I wanted the function to behave sensible when used in scalar context, I'd make it so. But I doubt that it would then return the number of elements of the list. I'm with rjbs on this one - the first (or last) element would be more usefu
    • by schwern (1528) on 2006.02.08 4:28 (#46069) Homepage Journal

      If I wanted the function to behave sensible when used in scalar context, I'd make it so.


      The other way to look at that is "I want my functions to behave insensibly in scalar context unless I remember to make it so" which strikes me as a little peevish and definately not DWIM.

      That aside, here's something more concrete--how do you do that? Take this sample for example, which is much like the code I recently stumbled over...

              return sort { $a cmp $b }
                            map { normalize_date($_) }
                            keys %days_processed;

      How do you rewrite that so it returns the number of elements in scalar context without making it A) convoluted, B) repeat code or C) inefficient?


      Now, what really would be cool is the return an iterator, returning the elements of the list in sorted order.


      That would be cool (though I'd make the iterator more explicit, your example reminds me too much of each()) except it would work completely unlike every other Perl 5 built-in, particularly the other list processing functions map and grep.

      I believe Perl 6 is going the iterator route.
      • The other way to look at that is "I want my functions to behave insensibly in scalar context unless I remember to make it so" which strikes me as a little peevish and definately not DWIM.

        That sounds like for all functions that I design to return a list, I should take the trouble of figuring out what it they should do in list context.

        Sorry, but I pass. For functions where it makes sense, I do so. But for many, I won't. Consider the context to be a pre-condition - just like the arguments being passed in.