my ($max_file, $max_num); while (defined(my $file = )) { ($max_file, $max_num) = ($1, $2) if $file =~ /^(foo_(\d+)\.bar)$/ and (!defined $max_num or $2 > $max_num); } print "$max_file\n";