CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate: Re: [joeferns79] Error reading files from dir: Edit Log



Kenosis
User

Feb 1, 2014, 12:58 PM


Views: 14487
Re: [joeferns79] Error reading files from dir

The assistance you've been given is excellent. But in case you may be interested, the following provides an option using the module File::Find::Rule for descending into directories:

Code
use strict; 
use warnings;
use File::Find::Rule;
use File::Basename;

my $dir = '/home/tester1/logs/';
my @files = File::Find::Rule->file()->name('*.log')->maxdepth(2)->in($dir);

for my $path (@files) {
my ( $filename, $suffix ) = ( fileparse($path) )[ 0, 1 ];
my $out;

open my $FILE, '<', $path or die "$path: $!\n";

while (<$FILE>) {
if (/^\Q<string to search>\E/) {
open $out, '>', $suffix . "report_$filename.txt" unless defined $out;
print $out $_;
}
}
close $out if defined $out;
close $FILE;
}

maxdepth() is set to 2, so it'll descend just below the top level. Without this parameter, it'll go as deep as the existing directory structure.

Another change is that a report file is created only if a match is found within the file it's examining. Without doing this, the script would create empty report files for files with no matches.

Lastly, note that \Q ... \E is used in the matching regex. This quotes (escapes) any meta-characters which may be present in the search string.

Hope this helps!


(This post was edited by Kenosis on Feb 1, 2014, 5:59 PM)


Edit Log:
Post edited by Kenosis (User) on Feb 1, 2014, 1:00 PM
Post edited by Kenosis (User) on Feb 1, 2014, 1:48 PM
Post edited by Kenosis (User) on Feb 1, 2014, 1:49 PM
Post edited by Kenosis (User) on Feb 1, 2014, 1:51 PM
Post edited by Kenosis (User) on Feb 1, 2014, 5:56 PM
Post edited by Kenosis (User) on Feb 1, 2014, 5:59 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives