To filter elements of an array based on a condition in Perl, you can use built-in functions like grep or map along with subroutines or anonymous functions.
In this example,
@numbers
containing integers.grep
function with an anonymous subroutine to filter out even numbers into a new array named @even_numbers
.@numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
@even_numbers = grep { $_ % 2 == 0 } @numbers;
print "Even Numbers: @even_numbers\n";
Even Numbers: 2 4 6 8 10
In this example,
@words
containing strings.grep
function with an anonymous subroutine to filter strings by their length into a new array named @filtered_words
.@words = ("apple", "banana", "cherry", "date", "fig");
@filtered_words = grep { length($_) > 5 } @words;
print "Filtered Words: @filtered_words\n";
Filtered Words: banana cherry
In this tutorial, we learned How to Filter Elements of an Array based on a Condition in Perl language with well detailed examples.