- Perl ›
- builtin functions ›
- here
grep function - Get only array elements that meet certain conditions
You can use the " grep function " to retrieve only the elements that match the conditions in the array. Each element of @array is passed to the default argument $_. Only elements that meet conditional statement will be added to @matched.
# Extract only the elements that match the conditions @matched = grep {conditional statement} @array;
Example
This is an example to get only the elements that match regular expression. In this example, only integers are taken. If @nums is (1.23, 123, 43) then @matched will be (123, 43).
# Get only the elements that match the regular expression my @nums = (1.23, 123, 43); my @matched = grep {/^\d+$/} @nums;
If the pattern matching operator (=~ ) is omitted in the regular expression, the default variable $_ will be the target of pattern matching. The example above has the same meaning as:
# Explicitly specify the default variable $_ my @matched = grep {$_ =~ /^\d+$/} @nums;
This is an example to get only multiples of 2. If @nums is (1, 2, 3, 4) then @even is (2, 4).
# Get only multiples of 2 my @nums = (1, 2, 3, 4); my @even = grep {$_ % 2 == 0} @nums;
Processing using grep can be written using foreach statement. Grep is often used in Perl because it is easier to write.
# for my @nums = (1.23, 123, 43); my @matched; for my $num (@nums) { push @matched, $num if $num =~ /^\d+$/; }
Reference "Array of Perl"
See below for a description of Perl's "arrays".