Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Unhappy returns

by ysth (Canon)
on Oct 10, 2005 at 04:34 UTC ( [id://498712]=note: print w/replies, xml ) Need Help??


in reply to Unhappy returns

It is worth noting, however, that, contrary to map, grep evaluates its second argument in scalar context:
And contrary to grep and map, foreach evaluates its body in void context:
$ perl sub ctx { print wantarray ? "list" : defined wantarray ? "scalar" : "v +oid" } @x = (1); print "map:"; map ctx, @x; print "\ngrep:"; grep ctx, @x; print "\nfor:"; ctx for @x; __END__ map:list grep:scalar for:void

Replies are listed 'Best First'.
Re^2: Unhappy returns
by thor (Priest) on Oct 10, 2005 at 11:59 UTC
    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

      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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://498712]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-04-25 10:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found