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: Beginner: Re: [naven8] Need help on opening multiple file with same file handle: Edit Log



budman
User

Mar 15, 2012, 10:29 PM


Views: 748
Re: [naven8] Need help on opening multiple file with same file handle

The opendir function will grab the dir headers, . and .. as well as sub dir names, so you need to filter those out. If you need to find files based on filemasks and do recursive searching, look into using File::Find (there is a util call find2perl that will spit out the code to use for you find function).

I use a matching string !/^\./ to skip anything that begins with a dot, this will exclude hidden files as well. If they are important, then you can change the grep statement to: grep{!/^\.{1,2}$/}readdir($DH) this will skip only . and ..


Code
 
my $dir = "/home/xyz";
opendir(my $DH,$dir) or die "Unable to open $dir\n$!";
my @Files = grep { !/^\./ && -f "$dir/$_" } readdir($DH);
closedir($DH);


If you wanted to make the file opening a little less brutal,
you can open files within the if statement.


Code
 
foreach my $Fi (@Files){
if ( open( my $FH,'<',$Fi ) ) {
print "$Fi is ok\n";
# Do some stuff
close($FH);
}
else {
print "Error: cannot open $Fi\n";
}
}


This way you can test which files are good and bad.


(This post was edited by budman on Mar 15, 2012, 10:37 PM)


Edit Log:
Post edited by budman (User) on Mar 15, 2012, 10:37 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