use File::Basename; my @files = reverse ; my $found; foreach ( @files ) { chomp; next unless basename($_) =~ m/^(\d+)$/; $found = $1; last; } die "No matches found.\n" unless defined $found; 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