#!/usr/bin/perl use strict; use warnings; chomp (my @lines = ); for my $i (0 .. $#lines) { (my $re = $lines[$i]) =~ s/_/|/g; # create $re outside the inner loop for my $j ($i + 1 .. $#lines) { my $count = () = $lines[$j] =~ /$re/g; if ($count >= 2) { print "$lines[$i] and $lines[$j]\n"; } } } __DATA__ one_two one_three_two three_one one_four four_three_one