use strict; use warnings; use File::Basename qw( fileparse ); my $first=''; my $second=''; while () { $first = $second; (undef, $second) = fileparse( $_ ); print "$second\n" if eof DATA; next unless $first; unless ( $second =~ /\Q$first/) { print "$first\n"; } } __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/test.txt hellotest/