Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of Perl's map?

Not really getting the point of the map function. Can anyone explain with examples its use?

Are there any performance benefits to using this instead of a loop or is it just sugar?

like image 935
Brian G Avatar asked Sep 25 '08 21:09

Brian G


People also ask

What does map do in Perl?

map() function in Perl evaluates the operator provided as a parameter for each element of List. For each iteration, $_ holds the value of the current element, which can also be assigned to allow the value of the element to be updated.

What does QW do in Perl?

The qw operator in Perl is used to extract each element of the given string as it is in an array of elements in single-quote ( ' ' ). This function stands for quote word because it considers each word of the given string as it is quoted like qw(Geeks for Geeks) is equivalent to ('Geeks', 'for', 'Geeks').

What is $_ in Perl?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }

What is associative array in Perl?

Associative arrays are a very useful and commonly used feature of Perl. Associative arrays basically store tables of information where the lookup is the right hand key (usually a string) to an associated scalar value. Again scalar values can be mixed ``types''.


1 Answers

Any time you want to generate a list based another list:

# Double all elements of a list my @double = map { $_ * 2 } (1,2,3,4,5); # @double = (2,4,6,8,10); 

Since lists are easily converted pairwise into hashes, if you want a hash table for objects based on a particular attribute:

# @user_objects is a list of objects having a unique_id() method my %users = map { $_->unique_id() => $_ } @user_objects; # %users = ( $id => $obj, $id => $obj, ...); 

It's a really general purpose tool, you have to just start using it to find good uses in your applications.

Some might prefer verbose looping code for readability purposes, but personally, I find map more readable.

like image 63
Adam Bellaire Avatar answered Sep 20 '22 11:09

Adam Bellaire