To filter items of a set based on a condition in Perl, you can iterate through the set and selectively add items that satisfy the condition to a new set.
In this example,
@numberSet
with values (1, 2, 3, 4, 5, 6)
.@evenNumbers
.@numberSet
using a foreach
loop.%
.@evenNumbers
set.my @numberSet = (1, 2, 3, 4, 5, 6);
my @evenNumbers;
foreach my $num (@numberSet) {
if ($num % 2 == 0) {
push @evenNumbers, $num;
}
}
print join(", ", @evenNumbers);
2, 4, 6
In this example,
@stringSet
with values ("Apple", "Banana", "Apricot", "Orange")
.@filteredStrings
.@stringSet
using a foreach
loop.index()
function.@filteredStrings
set.my @stringSet = ("Apple", "Banana", "Apricot", "Orange");
my @filteredStrings;
foreach my $str (@stringSet) {
if (index($str, 'A') == 0) {
push @filteredStrings, $str;
}
}
print join(", ", @filteredStrings);
Apple, Apricot
In this tutorial, we learned How to Filter Items of a Set based on a Condition in Perl language with well detailed examples.