I’ve been writing perl code full-time for a couple months now(bioinformatics), and am always trying to improve my skills. Just today, it dawned on me that I never use map or grep. Looking back through my code I realize these tools could save me a couple lines here or there, but only at the expense of the flexibility of a foreach loop. My question is as follows:
Are there any circumstances you have run across where using map or grep has brought significant advantage over a foreach/for loop, beyond saving a line or two of code?
Thanks for your time!
The Schwartzian Transform would be an example:
You could do that with a pile of
foreachloops but you’d have to pick them apart to figure out what was going on; once you’ve seen the Schwartzian Transform you recognize the idiom immediately.In general I think
mapandgrepare good in that they allow you to clearly and compactly represent your intent without layers of syntax. If you see amapthen you know that some sort of simple data structure transformation is going on; if you see agrepthen you know that some filtering/selection is going on. You could do it all withforeachbut the intent of your code isn’t as clear as it would be withmaporgrep; you could even do it all withifandgotoif you wanted to but then your intent would be buried under even more syntax and state tracking.