use File::Basename; my $found; while( ) { chomp; my $bn = basename($_); next unless $bn =~ m/^\d+$/; $found = $bn; } print $found; __DATA__ /path/to/one/library /path/to/another /path/to/another/01 /path/to/another/s /path/to/another/02 /path/to/another/w1 /path/to/another/03 /path/to/another/1e /path/to/another/2014