my $switchdir = '/some/path'; my $host_hi = qr/some pattern of interest/; my $hba_alias; my $found_name; for my $name ( <$switchdir/*.swc> ) { open my $in, '<', $name or do { warn "unable to open $name: $!\n"; next; }; while (<$in>) { if ( /$host_hi/ and /:\s+device-alias/ ) { $hba_alias = $_; $found_name = $name; last; } } last if $hba_alias; # as soon as we find a match, we're done } print "match found in $found_name: $hba_alias";