In Perl, you can find the intersection of two sets using the built-in hash data structure and the keys function to extract the common elements.
In this example,
my %set1 = map { $_ => 1 } qw(1 2 3 4);
my %set2 = map { $_ => 1 } qw(3 4 5 6);
my @intersection = grep { $set2{$_} } keys %set1;
print "Intersection of set1 and set2: @intersection\n";
Intersection of set1 and set2: 3 4
In this example,
my %set1 = map { $_ => 1 } qw(1 2 2 3 4);
my %set2 = map { $_ => 1 } qw(2 2 3 4 5);
my @intersection = grep { $set2{$_} } keys %set1;
print "Intersection of set1 and set2 with duplicates: @intersection\n";
Intersection of set1 and set2 with duplicates: 2 2 3 4
In this tutorial, we learned How to find Intersection of Two Sets in Perl language with well detailed examples.