Ignoring "without opening these files", what do you want returned: the name of the files with a matching pattern, or the matching lines from the files?
Version that outputs the name of the files with a matching pattern:
use File::Glob qw( bsd_glob );
# Inputs
my @files = bsd_glob('*');
my $re = qr/^source*/;
my @matching_files;
foreach my $file_name (@files) {
if (!open(my $fh, '<', $file_name)) {
warn("Unable to open file \"$file_name\": $!\n");
next;
}
while (<$fh>) {
if (/$re/) {
push(@matching_files, $file_name);
last;
}
}
}
# Output
print("$_\n")
foreach @matching_files;
Version that outputs the line that match the pattern.
use File::Glob qw( bsd_glob );
# Inputs
my @files = bsd_glob('*');
my $re = qr/^source*/;
my @matching_lines;
foreach my $file_name (@files) {
if (!open(my $fh, '<', $file_name)) {
warn("Unable to open file \"$file_name\": $!\n");
next;
}
while (<$fh>) {
if (/$re/) {
push(@matching_lines, $_);
}
}
}
# Output
print
foreach @matching_lines;
A combination:
use File::Glob qw( bsd_glob );
# Inputs
my @files = bsd_glob('*');
my $re = qr/^source*/;
my @matches;
foreach my $file_name (@files) {
if (!open(my $fh, '<', $file_name)) {
warn("Unable to open file \"$file_name\": $!\n");
next;
}
while (<$fh>) {
if (/$re/) {
# Save the file name, the line number and the line content.
push(@matches, [ $file_name, $., $_ ]);
}
}
}
# Output
print($_->[0], ',', $_->[1], ': ', $_->[2])
foreach @matches;
These solutions are memory efficient.
(Returning the results as an iterator would be even more!)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.