perl function grep

https://w‮.ww‬theitroad.com

The grep function in Perl is used to filter a list of values based on a specific criterion. It takes a code block or an expression that evaluates to a Boolean value and returns a new list containing only those elements that match the criteria.

Here's an example that demonstrates how to use grep:

#!/usr/bin/perl

use strict;
use warnings;

# Define an array of numbers
my @numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

# Use grep to filter the array for even numbers
my @even_numbers = grep { $_ % 2 == 0 } @numbers;

# Print the filtered array
print "Even numbers: @even_numbers\n";

In this example, we start by defining an array called @numbers that contains the numbers 1 to 10. We then use the grep function to filter the array for even numbers by passing a code block that tests whether each element is divisible by 2. The $_ variable refers to the current element being tested. The grep function returns a new array containing only the even numbers. Finally, we print the filtered array to the console.

Note that the grep function does not modify the original array. Instead, it returns a new array containing only the elements that match the criteria.