In Perl, both
grep and map iterate over a list of items and temporarily set the $_ variable to each element, but they serve completely different purposes: grep is used for filtering, while map is used for transforming.grep (The Filter)
grep evaluates a block of code (or an expression) for each element in a list. If the expression evaluates to true, the original element is included in the new list.- Primary Use: When you want a specific subset of your original list.
- Output: A list containing only the elements that passed the test.
my @numbers = (1, 2, 3, 4, 5, 6);
# Extract only the even numbers
my @evens = grep { $_ % 2 == 0 } @numbers;
# @evens contains: (2, 4, 6)
map (The Transformer)
map evaluates a block of code (or an expression) for each element in a list and returns the result of that evaluated expression, building a new list out of those results.- Primary Use: When you want to modify every item in a list or extract specific data from complex structures.
- Output: A new list containing the transformed values.
my @numbers = (1, 2, 3, 4, 5, 6);
# Multiply every number by 10
my @multiplied = map { $_ * 10 } @numbers;
# @multiplied contains: (10, 20, 30, 40, 50, 60)
Side-by-Side Comparison
The best way to see the difference is to apply the exact same operation to a list using both functions. Let's try to convert an array of strings to uppercase:
my @words = ("apple", "banana", "cherry");
# 1. Using grep
my @using_grep = grep { uc($_) } @words;
# Result: ("apple", "banana", "cherry")
# Why? uc($_) successfully returns a string, which evaluates to "true" in Perl.
# Because it's true, grep returns the ORIGINAL unmodified elements.
# 2. Using map
my @using_map = map { uc($_) } @words;
# Result: ("APPLE", "BANANA", "CHERRY")
# Why? map returns the actual RESULT of the uc($_) expression for each item.
No comments:
Post a Comment