go ahead... be a heretic | |
PerlMonks |
Re: Help me decipher code containing map functionby Marshall (Canon) |
on May 20, 2017 at 08:24 UTC ( [id://1190703]=note: print w/replies, xml ) | Need Help?? |
I believe that BrowserUk and AnomalousMonk clearly have the best code to use in place of your code from the class: Shorter, more clear, runs faster. I would like to make a few comments about map. All maps can be written as "foreach" loops. Use "for" instead of "foreach" if you want - these keywords mean exactly the same. The code that you started with uses what is called a "bare map", a map which does not make use of the potential output list. Most maps are like: @out_array = map{func..}@in_array; In your case, there is no @out_array and the map function works because of side-effects within the map's code. In this case $val is being modified. I re-wrote the map code into a foreach loop as a demo. This allows you to add print statements to see what the loop is doing. And of course since this is a foreach loop, the $_ variable can be some other name (also see below). Performance between a map and a foreach version should be similar. I personally only use map for short transformation operations, perhaps making a hash table from a list of values my %hash = map{$_ => 1}@list;. In this hash table case, the code is a "one liner" that makes use of the map's output, i.e. it is not a "bare" map. I don't use map's that do not make use of the left hand assignment. I have seen map functions with 20 lines of code. Again, I would recommend a foreach loop in that situation. I hope the demo code below helps:
In Section
Seekers of Perl Wisdom
|
|