http://qs1969.pair.com?node_id=597459


in reply to search for a pattern in file without opening the file

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!)