in reply to Re^3: Value of a statement with modifier (unless)
in thread Value of a statement with modifier

Indeed, thanks for posting; I have now modified Perl 6 to fix this problem today--it no longer returns the last expression evaluated, but the value of the last statement in the block. Happily, fixing this (and a few other things) also makes list comprehensions a lot easier to write now.

How will that work with a for modifier? I've occasionally wanted

$t += $_ for @list;

to return the last value of $t. Okay, okay, I know in Perl 6 there will be other ways to do similar stuff, in particular functional-language like ones that will avoid the need for a temporary variable altogether, but I still wonder how this kind of situation will be handled...

Replies are listed 'Best First'.
Re^5: Value of a statement with modifier (unless)
by TimToady (Parson) on Jan 25, 2007 at 18:00 UTC
    How will that work with a for modifier? I've occasionally wanted

    $t += $_ for @list;

    to return the last value of $t. Okay, okay, I know in Perl 6 there will be other ways to do similar stuff, in particular functional-language like ones that will avoid the need for a temporary variable altogether, but I still wonder how this kind of situation will be handled...

    Hmm, well, in my copy of Perl that doesn't return $t, but the notional undef off the end of the list, which again points out the same semantic problem of "what's the last expression, anyway?"

    But yes, in Perl 6 you'd just write:

    [+] @list
    to sum up the values. As for what your snippet would actually return in Perl 6, with the new rules I'd expect it to return the list of intermediate values, much as if you'd used a "triangular reduce":
    [\+] @list
    But generally if you're in that situation you'd be using the temporary value later anyway, which tends to put the for loop into void context, so it knows it can just throw away all those intermediate values. And arguably if you're using something as subtle as returning the last value of a for loop, you should have at least a return $t after it for clarity, which would also put the loop into void context. I think this approach will turn out more intuitive in the long run, though of course over the short term it runs a bit counter to Perl 5 intuitions. These days when we try to balance the needs of the present with the needs of the future, we tend to put a thumb on the scale in favor of the future. :-)