Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^2: search for a pattern in file without opening the file (iter)

by ikegami (Pope)
on Jan 30, 2007 at 23:17 UTC ( #597466=note: print w/replies, xml ) Need Help??


in reply to Re: search for a pattern in file without opening the file (mem efficient)
in thread search for a pattern in file without opening the file

Here's a version that only keeps one line in memory at a time (as opposed to every match). It is done elegantly (from the perspective of the function's user) using an iterator.

use strict; use warnings; use File::Glob qw( bsd_glob ); sub search_files { my ($re, @files) = @_; my $fh; my $file_name; return sub { START: if (not defined $file_name) { return () if not @files; $file_name = shift(@files); if (!open($fh, '<', $file_name)) { warn("Unable to open file \"$file_name\": $!\n"); undef $file_name; goto START; } } while (defined(my $line = <$fh>)) { if ($line =~ /$re/) { return ( $file_name, $., $line ); } } undef $fh; undef $file_name; goto START; }; } { my @files = bsd_glob('*'); my $re = qr/^source*/; my $iter = search_files($re, @files); while (my ($file_name, $line_num, $line) = $iter->()) { print("$file_name,$line_num: $line"); } }
  • Comment on Re^2: search for a pattern in file without opening the file (iter)
  • Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://597466]
help
Chatterbox?
[Corion]: marto: Oh, I'm jealous. I'm going to see DM in Frankfurt, but it's a stadium full of people, so, rather a big thing where you mostly get to see the band on screens ;)
[marto]: yes, the last time I saw them was in Berlin a few years ago, at the old Olympic stadium
[marto]: After Sunday I don't think I'll go see them again :)
[LanX]: Corion: come on, people are people! ;)
[Corion]: Naah, I think it's still an OK show so far. Their new songs aren't exactly great, but I'm not going there for new material anyway ;)

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (14)
As of 2017-03-24 11:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (301 votes). Check out past polls.