On Thu, Mar 20, 2008 at 11:46 AM, Sharan Basappa <[EMAIL PROTECTED]> wrote: > Can you throw some light on this statement: > > my %hashset = map { $_ => 1 } @array; snip
The map* function takes a block of code and a list to process. It runs the block of code on every item in the list returning a list of the outputs of the block. So saying map { "hi $_" } (1,2,3) is the same as saying ("hi 1", "hi 2", "hi 3") The number of items returned from each running of the block does not need to be 1, you can return more than one item: map { $_, $_ ** 2, $_ ** 3 } (1,2,3) is the same as (1, 1, 1, 2, 4, 8, 3, 9, 27) You can even return no items: my @even = map { $_ % 2 ? () : $_ } (1 .. 10); although, in this case, grep** (a similar function) works better: my @even = grep (not $_ % 2 } (1 .. 10); The initialization value for a hash is a list holding pairs of items to be interpreted as a key and a value. You can generate such a list for a hash set by simply interleaving your original list with ones: ("foo", "bar", "baz") would be ("foo", 1, "bar", 1, "baz", 1). The map function provides an easy way to do this: my %hashset = map { $_, 1 } @list; Now, the fat comma (=>) is more commonly associated with hashes, so it is prettier to say my %hashset = map { $_ => 1 } @list; * http://perldoc.perl.org/functions/map.html ** http://perldoc.perl.org/functions/grep.html -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/