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.
  • by Abigail (26) on 2006.02.04 17:57 (#46014) Journal
    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 useful.

    Now, what really would be cool is the return an iterator, returning the elements of the list in sorted order. The function wouldn't be called again until the list was exhausted. Example:

    my @list = qw [foo bar baz];
    sub sortlist {
        print "Hello, world\n";
        return sort @list;
    }
    for (1 .. 5) {
        print scalar sortlist, "\n";
    }
    __END__
    Hello, world
    bar
    baz
    foo
    Hello, world
    bar
    baz

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

      • 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 would require of Perl to do extra magic when it encounters return sort, and it’s non-reentrant. I vote no. If you want an iterator, then an iterator object/closure should be returned. Let’s not create more instances of the each trap.