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

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner:
Need help on opening multiple file with same file handle



Mar 15, 2012, 1:35 PM

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


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?

use warnings; 
use strict;

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

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

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)


Mar 15, 2012, 10:29 PM

Post #2 of 2 (924 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 ..

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

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

foreach my $Fi (@Files){
if ( open( my $FH,'<',$Fi ) ) {
print "$Fi is ok\n";
# Do some stuff
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