Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: map grep and sort

by eyepopslikeamosquito (Chancellor)
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

Replies are listed 'Best First'.
Re^2: map grep and sort
by coyocanid (Sexton) 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1035201]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2018-05-23 16:00 GMT
Find Nodes?
    Voting Booth?