What’s the point of Perl’s map?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)