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:
Need help on opening multiple file with same file handle

 



naven8
Novice

Mar 15, 2012, 1:35 PM

Post #1 of 2 (785 views)
Need help on opening multiple file with same file handle Can't Post

Hi,

I have written following code and it is working fine. I would like to know whether it is a good thing to do or not?

Code
use warnings; 
use strict;

opendir(my $DH,"/home/xyz") or die "Unable to open $!";
my @Files = readdir($DH);
closedir($DH);

foreach my $Fi (@Files){
open my $FH,'<',$Fi or die "Unable to read $!";
# Do some stuff
close($FH);
}


Is it good? Is there any other good way of doing the same?

Thanks in advance.


(This post was edited by naven8 on Mar 15, 2012, 1:36 PM)


budman
User

Mar 15, 2012, 10:29 PM

Post #2 of 2 (779 views)
Re: [naven8] Need help on opening multiple file with same file handle [In reply to] Can't Post

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)

 
 


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

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