WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Perl · Intermediate · question 22 of 100

How do you use ’map’ and ’grep’ functions in Perl, and what are their benefits?

📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

In Perl, ‘map‘ and ‘grep‘ are two very powerful functions that allow for efficient manipulation and filtering of lists and arrays.

‘map‘ applies a specified function to every element in a list or array, and returns a new list or array containing the results. The syntax for the ‘map‘ function is as follows:

@new_list = map { function } @old_list;

Here, ‘function‘ is some operation that is to be performed on each element in ‘@old_list‘, and ‘@new_list‘ is the new list or array that is created. For example, suppose we have an array of numbers and we want to double each element:

my @numbers = (1, 2, 3, 4, 5);
my @doubled_numbers = map { $_ * 2 } @numbers;

In this case, we can use the ‘map‘ function to perform the doubling operation on each element of ‘@numbers‘ and store the results in a new array ‘@doubled_numbers‘.

‘grep‘, on the other hand, is used to filter elements out of a list or array, based on some specified condition. The syntax for the ‘grep‘ function is:

@new_list = grep { condition } @old_list;

Here, ‘condition‘ is some test that is performed on each element in ‘@old_list‘, and only those elements that satisfy the condition are included in the new list or array ‘@new_list‘.

For instance, we may have an array of numbers and want to filter out all the even numbers:

my @numbers = (1, 2, 3, 4, 5);
my @odd_numbers = grep { $_ % 2 != 0 } @numbers;

In this example, the ‘grep‘ function takes the array ‘@numbers‘ and filters out all the even numbers, based on the condition that ‘$_ % 2 != 0‘. Only the odd numbers remain in the new array ‘@odd_numbers‘.

Both ‘map‘ and ‘grep‘ functions are very efficient at handling large datasets because they work with the list of values without creating a new data structure. By using these functions, you can easily manipulate data with less effort and fewer lines of code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Perl interview — then scores it.
📞 Practice Perl — free 15 min
📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

All 100 Perl questions · All topics