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

    • 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 }
             

      • by Abigail (26) on 2006.02.08 17:12 (#46086) Journal
        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.

        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;
        Assuming that normalize_date returns a single value, I'd write that as:
            return wantarray ? sort {$a cmp $b}
                               map  {normalize_date $_}
                               keys %days_processed
                             : keys %days_processed;