FYI: you can use (0..$#cluster) rather than hardcoding magic numbers, and push onto the array to simplify your initialization (see below).
use strict;
use warnings;
Are important to include too.
Example (with array names pluralized for clarity):
use strict;
use warnings;
my @sets = (
[0],
[0, 1],
[0, 1, 2],
[1, 2, 3],
[5, 6, 4],
);
my @clusters;
foreach my $set (@sets)
{
push @clusters, Set::Scalar>new>insert(@$set);
}
for my $i (0.. $#clusters)
{
...
Definitely put some debug prints into your loop so you can see if what it is actually doing is what you expect it to be doing at each step.
PS:
If this is going to expand to large sets of clusters, it would probably be a good idea to modify your algorithm such that it doesn't have to check the cleared/empty sets over and over. For large clusters, you would want an intersection test that shortcircuits after the first match to return just a true/false result too.
I'd suggest having a list of superclusters, and adding one cluster at a time. If the new cluster has no intersections with anything, add it to the list as a new supercluster. If it has an intersection with something, add it to that supercluster and keep searching. For every intersection after the first, add the intersecting supercluster to the originally matched supercluster, and then completely remove the new match (take care about the list shrinking by 1 when you do that).
That way, your debug output could show something like:
0 superclusters: () : adding (0)... 0 intersections.
1 supercluster: ((0)) : adding (1,2,3)... 0 intersections.
2 superclusters: ((0), (1,2,3)) : adding (0,1)... 2 intersections.
1 supercluster: ((0,1,2,3)) : adding (0,1,2)... 1 intersection.
