http://www.perlmonks.org?node_id=675494


in reply to How do I un-map this code?

I have also tried to avoid the use of map because I really can never understand what it is doing

I translate this statement as "I'm scared, so I refuse to address my fear." If you really don't want to address your fear, stop now. I plan on getting you to understand map so that you never have to worry again.

map, grep, and sort all operate the exact same way. They take a list of stuff and return a list of stuff.

So, an example:

my @l = ( 5, 4, 3, 2, 1 ); my @sorted = sort { $a <=> $b } @l; # Sorted is ( 1, 2, 3, 4, 5 ) my @grepped = grep { $_ > 2 } @l; # Grepped is ( 5, 4, 3 ) my @mapped = map { $_ * 2 } @l; @ Mapped is ( 10, 8, 6, 4, 2 )

Now, the biggest problem people usually have with map and grep (though, funnily enough, not sort) is that you have to read them from right to left. This is in direct opposition to how you read everything else (which is from left to right). Perl 6 will provide a mechanism where you can have map, grep, and other list operators that can be read from left to right. It will look something like:

my @l = ( 5, 4, 3, 2, 1 ); @l ==> grep { $_ > 2 } ==> sort { $a <=> $b } ==> map { $_ * 2 } ==> @final; # Final contains ( 6, 8, 10 )
Is that easier to read?

Oh, and fearing unless is just plain old laziness - the bad kind. unless(...) is exactly identical to if(!(...)). Nothing less, nothing more. Feel free to revise as desired.


My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?