Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: map grep and sort

by eyepopslikeamosquito (Canon)
on May 24, 2013 at 20:55 UTC ( #1035201=note: print w/ replies, xml ) Need Help??


in reply to map grep and sort

Inside the filtering block, the list element being examined is set to the default variable $_
To be more precise, $_ is an alias to the list element.

Map takes each item from the list on the right and passes the return value from its block to the left. It does not transform the items on the list even if it feels like that.
That is not correct. From map:
Note that $_ is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables.

Note however that Effective Perl Programming, item 20, cautions against this:

For efficiency, $_ is actually an alias for the current element in the iteration. If you modify $_ within the transform expression of a map, you modify the input data. This is generally considered to be bad style, and -- who knows? -- you may even wind up confusing yourself this way. If you want to modify the contents of a list, use foreach.

BTW, in the same item, "Use foreach, map and grep as appropriate", Effective Perl Programming provides a nice summary of when to use foreach, map and grep:

  • Use foreach to iterate read-only over each element of a list
  • Use map to create a list based on the contents of another list
  • Use foreach to modify elements of a list
  • Use grep to select elements in a list


Comment on Re: map grep and sort
Select or Download Code
Re^2: map grep and sort
by coyocanid (Acolyte) on May 24, 2013 at 21:16 UTC
    I agree. I should change the text to note $_ being an alias and change the 'does not transform' into 'Should not be used to transform'

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2014-10-02 02:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (43 votes), past polls