my $digit_width = 4; my $min = 1; my $max = 12; my $prefix = "test_"; my $ext = ".txt"; while ( my $file = readdir DIR ) { next unless ( $file =~ /^ $prefix (\d{$digit_width}) $ext $/x ); if ( $1 >= $min and $1 <= $max ) { # we have a match... now what? } }