In Perl, you can use the built-in Set::Scalar module to work with sets and perform set operations.
In this example,
Set::Scalar
module by importing it with the use
keyword.Set::Scalar
objects, $set1
and $set2
, and add elements to them using the insert
method.union
method of $set1
to find the union with $set2
and store the result in $unionSet
.$unionSet
to display the union of the two sets.use Set::Scalar;
my $set1 = Set::Scalar->new(1, 2, 3);
my $set2 = Set::Scalar->new(3, 4, 5);
my $unionSet = $set1->union($set2);
print "Union of set1 and set2:\n";
print "$unionSet\n";
Union of set1 and set2: {1, 2, 3, 4, 5}
In this example,
@set1
and @set2
, to represent the sets.unionSets
that takes references to @set1
and @set2
as parameters.unionSets
subroutine, we iterate over each element of @set2
and push it into @set1
if it's not already present.unionSets
subroutine with references to @set1
and @set2
.join
function to concatenate the elements of @set1
and print the result to display the union set.sub unionSets {
my ($set1_ref, $set2_ref) = @_;
my %union = map { $_ => 1 } @{$set1_ref}, @{$set2_ref};
return keys %union;
}
my @set1 = (1, 2, 3);
my @set2 = (3, 4, 5);
my @unionSet = unionSets(\@set1, \@set2);
print "Union of set1 and set2:\n";
print join(', ', @unionSet), "\n";
Union of set1 and set2: 1, 2, 3, 4, 5
In this tutorial, we learned How to find Union of Two Sets in Perl language with well detailed examples.