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?
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.
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').
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"; }
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''.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With