in reply to Re: Unhappy returns
in thread Unhappy returns

And contrary to grep and map, foreach evaluates its body in void context
Isn't the comparison a little unfair? map and grep are operators, whereas for is a looping construct

thor

Feel the white light, the light within
Be your own disciple, fan the sparks of will
For all of us waiting, your kingdom will come

Replies are listed 'Best First'.
Re^3: Unhappy returns
by Perl Mouse (Chaplain) on Oct 10, 2005 at 12:53 UTC
    Well, map and grep are usually seen as functions, but there's no denying that both map and grep are looping constructs.

    But ultimely, what is the difference between an operator, a function or a syntax construct from a programmers aspect of view (other than using it to answer "where do I find this in the manual")? Would you code differently if map or grep were reclassified as a syntax or looping construct, or foreach as a function?

    Perl --((8:>*

      The difference is that foreach is a statement, and as such does not return anything. The context in which its body is evaluated is therefore never of any interest, any more than it is of interest which context the body of an if or while is evaluated in.

      map and grep OTOH are expressions and do return something; which means context is paramount.

      Makeshifts last the longest.

        I'd have to disagree. Every runtime statement in perl does have a return value. It's not true that foreach doesn't return anything. Ponder this piece of code:
        @x = sub { 0; for (4,3,2) { 1 } }->();
        What does the sub return? Is it a bug? What should it return? (It has to return something, even if it's an empty list.) Also compare to
        @x = sub { }->();
        and
        $x = sub { 0; for (4,3,2) { 1 } }->();