Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read all files in a directory in perl

Tags:

file

perl

in the first part of my code, I read a file and store different parts of it in different files in a directory and in the following I wanna read all the files in that directory that I build it in the first part of code:

while(<file>){

#making files in directory Dir

}

opendir(Dir, $indirname) or die "cannot open directory $indirname";
@docs = grep(/\.txt$/,readdir(Dir));
foreach $d (@Dir) {
    $rdir="$indirname/$d";
    open (res,$rdir) or die "could not open $rdir";
    while(<res>){


}

but with this code, the last line of the last file wont be read

like image 411
Fatimah Avatar asked Apr 13 '11 15:04

Fatimah


1 Answers

I modified the code slightly to just test the basic idea in a directory containing my perl programs and it does seem to work. You should be iterating through @docs instead of @dir though (and I highly recommend using both the strict and warnings pragmas).

opendir(DIR, ".") or die "cannot open directory";
@docs = grep(/\.pl$/,readdir(DIR));
foreach $file (@docs) {
    open (RES, $file) or die "could not open $file\n";
    while(<RES>){
        print "$_";
    }
}
like image 118
Cooper Avatar answered Sep 30 '22 17:09

Cooper