>>>>> "sw" == shawn wilson <ag4ve...@gmail.com> writes:
sw> On Tue, Jan 11, 2011 at 4:57 AM, Sean Murphy <mhysnm1...@gmail.com> wrote: >> Hi all. >> >> I have read the explaination of the Map function and it is still a mystry to >> myself on what it is for and when would you use it? >> >> All explainations I have seen in books and blogs don't make it clear. >> sw> my @new = map {$_} @arr; sw> is the same as: sw> foreach (@arr) { sw> push $_, @new; sw> } sw> in other words, do something to every element of an array. that is a poor explanation IMO. map transforms one list into another. it is that simple but it is very useful. you can alway write map in terms of a perl loop but it will be slower and clunkier in most cases. map take an input list, it aliases $_ to each element (an implied loop) and then executes the block or expression. it collects the results of that code and builds up a list which it returns when the input elements are exhausted. the key to understanding map is that the expression can return 0, 1 or more elements EACH time through. so the complete map call can return ANY number of elements, regardless of the number of input elements. if the expression returns 0 or 1 elements, it is similar to perl's grep: these are equivilent: my @out = grep /foo/, @in ; my @out = map { /foo/ ? $_ : () } @in ; but map can do much more than grep. grep can ONLY return its input list or some elements of it. map can generate more elements: this builds a hash of 3 keys, each which has the value 1. it can be used to test if something is one of the keys with a simple boolean. my %is_a_foo = map { $_ => 1 } qw( foo bar baz) ; if ( $is_a_foo( $stuff ) { .... map is very simple when you really get it and very useful. it should be in all perl hacker's skill sets. for some reason newbies have trouble with it but that is usually due to poor explanations and not knowing about functional programming (map comes from lisp which has similar map funcs). map's name comes from its role in mapping one list into another. that should help too. uri -- Uri Guttman ------ u...@stemsystems.com -------- http://www.sysarch.com -- ----- Perl Code Review , Architecture, Development, Training, Support ------ --------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com --------- -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/