use strict; use warnings; use File::Basename qw( fileparse ); my %seen; while () { (undef, my $path) = fileparse( $_ ); print "$path\n" unless $seen{$path}++; } print "="x70,"\n"; foreach my $key (keys %seen){ print "$key\n" if 1 == scalar grep { /\Q$key/ } keys %seen; } __DATA__ testing123/ foobar/ helloworld/ helloworld/r1/ helloworld/r1/helloworld-5-0.noarch.rpm helloworld/r1/testfile23.txt helloworld/r1/tomcat-7.0.27.rpm helloworld/r2/ helloworld/r2/helloworld-2-0.noarch.rpm helloworld/r2/testfile12.txt helloworld/r2/tomcat-5.0.52.rpm hellotest/