Based on the OP snippets, it looks like you just want a small amount of output from all those input files: if the value of "$host_hi" occurs together with ": device-alias" in any of the *.swc files, you only keep the first line of the first file where the match was found. If that's all you really need, you can save a lot of time by only reading data until a match is found:
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";
(updated to make sure the matched file name would be accessible after exiting the for loop)
As for grepping in individual files for other patterns (and assigning initial matches, if any, to other variables), it depends on what you really are doing, but I'd be inclined to set up a hash of file names with patterns to search for, and would use that to store matches that are found, as well:
my %seeking = (
$switchfqdn => { regex => qr/^fc.*?$hba_wwn/ },
...
);
for my $filename ( keys %seeking ) {
open my $in, '<', $filename or do {
warn "$filename: $!\n";
next;
};
while (<$in>) {
if ( /$seeking{$filename}{regex}/ ) {
$seeking{$filename}{found} = $_;
last;
}
}
if ( $seeking{$filename}{found} ) {
print "found in $filename: $seeking{$filename}{found}";
else {
warn "no matches in $filename for $seeking{$filename}{regex}\n
+";
}
}
And if any of the specific file searches involve *.swc files, there's probably a reasonable way to include the file-specific searches inside the loop that handles all *.swc files, so that if you happen to be looking for more than one pattern in a given file, you can get all the results you want without having to read any file more than once.
One more update: you didn't give any clues about what sorts of patterns you're looking for, but reading the file contents in perl and applying perl regexes to the data is both a lot safer and a lot more flexible than trying to interpolate a regex onto a shell command line that you pass to a system() call. Using things like backslashes, whitespace, parens, brackets, *? and so on is pretty common in regexes, and pretty hard to control when passing stuff to a shell. |