Read all files in a directory in perl
in the first part of my code, I read a file and store different parts of it 开发者_如何学Pythonin 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
As I don't know what you are doing in the line reading loop and don't understand @docs and @Dir, I'll show code that 'works' for me:
use strict;
use warnings;
use English;
my $dir = './_tmp/readFID';
foreach my $fp (glob("$dir/*.txt")) {
printf "%s\n", $fp;
open my $fh, "<", $fp or die "can't read open '$fp': $OS_ERROR";
while (<$fh>) {
printf " %s", $_;
}
close $fh or die "can't read close '$fp': $OS_ERROR";
}
output:
./_tmp/readFID/123.txt
1
2
3
./_tmp/readFID/45.txt
4
5
./_tmp/readFID/678.txt
6
7
8
Perhaps you can spot a relevant difference to your script.
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 "$_";
}
}
glob
does what you want, without the open/close stuff. And once you stick a group of files into @ARGV
the "diamond" operator works as normal.
@ARGV = <$indirname/*.txt>;
while ( <> ) {
...
}
精彩评论