To create a Set of Sets in Perl, you can use nested hashes to represent sets. You create individual sets as keys in a hash and then add them to another hash.
In this example,
%set1
, %set2
, and %set3
. We add the elements 1, 2, 3
to %set1
, 4, 5, 6
to %set2
, and 7, 8, 9
to %set3
.%set_of_sets
and add %set1
, %set2
, and %set3
to it. This nests the three sets within a single hash.%set_of_sets
using a foreach loop. Within the loop, we print each individual set to the standard output.my %set1 = map { $_ => 1 } (1, 2, 3);
my %set2 = map { $_ => 1 } (4, 5, 6);
my %set3 = map { $_ => 1 } (7, 8, 9);
my %set_of_sets = (set1 => %set1, set2 => %set2, set3 => %set3);
foreach my $set (values %set_of_sets) {
print join(", ", keys %{$set}), "\n";
}
Output: 1, 2, 3 4, 5, 6 7, 8, 9
In this example,
%setA
, %setB
, and %setC
. We add the elements "apple", "banana", "cherry"
to %setA
, "dog", "elephant", "fox"
to %setB
, and "grape", "honeydew", "kiwi"
to %setC
.%set_of_string_sets
and add %setA
, %setB
, and %setC
to it. This nests the three sets within a single hash.%set_of_string_sets
using a foreach loop. Within the loop, we print each individual set to the standard output.my %setA = map { $_ => 1 } ("apple", "banana", "cherry");
my %setB = map { $_ => 1 } ("dog", "elephant", "fox");
my %setC = map { $_ => 1 } ("grape", "honeydew", "kiwi");
my %set_of_string_sets = (setA => %setA, setB => %setB, setC => %setC);
foreach my $set (values %set_of_string_sets) {
print join(", ", keys %{$set}), "\n";
}
Output: banana, cherry, apple elephant, fox, dog kiwi, honeydew, grape
In this tutorial, we learned How to create a Set of Sets in Perl language with well detailed examples.