@new = ('Al'); while(@new){ $key = shift @new; push @old, $key; @friends = (select col1 from table where col2 = $key, select col2 from table where col1 = $key); %unique = (); @unique{@friends} = undef; delete @unique{@new, @old}; push @new, keys %unique; }