in reply to Re: "last expression" quiz
in thread "last expression" quiz

It’s probably safe to say that Perl simply has no rule here, and that what you get back from a sub depends on implementation details of perl.
Wouldn't it be more accurate to say that returning the value from the last expression in subs works fine. But statements (things like if, for, while) don't have values and return pretty much garbage?

Replies are listed 'Best First'.
Re^3: "last expression" quiz
by Aristotle (Chancellor) on Oct 20, 2005 at 02:34 UTC

    Maybe, but how do you reconcile that with the behaviour with if blocks, which work precisely as documented?

    Makeshifts last the longest.

      My point is mostly that the problem resides with how "for" is implemented, and not a problem with "sub" returning an incorrect value.
Re^3: "last expression" quiz
by sauoq (Abbot) on Oct 20, 2005 at 04:44 UTC
    But statements (things like if, for, while) don't have values and return pretty much garbage?

    Well, if works in that it returns the result of the last expression evaluated. It seems that's what looping constructs should do too. Wouldn't it make sense for this sub x { $_ for 10 } to return 10?

    -sauoq
    "My two cents aren't worth a dime.";
    
      Well, if works in that it returns the result of the last expression evaluated. It seems that's what looping constructs should do too. Wouldn't it make sense for this sub x { $_ for 10 } to return 10?
      Not really. If you're asking my opinion I'd say it should be an error if the sub is called in anything other than a void context. Note the following are also compilation errors...
      my $what = (if(1){print "true"}else{print "false"}); sub foo { return (for (1..3) { print $_ }); }
      You're not arguing that they shouldn't be, are you?
        You're not arguing that they shouldn't be, are you?

        No, I'm certainly not. I'm perfectly happy that those are errors. I don't know if it follows that sub x {$_ for 10} should be an error but I can see the argument for it. I see usefulness on both sides. Causing an error would be useful in preventing some god awful code while returning the result of the last expression evaluated would be useful in some god awful code. Usually, when there is a choice like that, Perl supports the latter but prints a warning under -w ... :-)

        -sauoq
        "My two cents aren't worth a dime.";