Read all files in the perl directory

in the first part of my code, I read the file and saved it in different files in the directory, and in the next I want to read all the files in this directory that I built in the first part of the 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 will not be considered

+8
file perl
source share
3 answers

Since I donโ€™t know what you are doing in the line reading loop and donโ€™t understand @docs and @Dir, I will show the 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"; } 

exit:

 ./_tmp/readFID/123.txt 1 2 3 ./_tmp/readFID/45.txt 4 5 ./_tmp/readFID/678.txt 6 7 8 

Perhaps you can find the corresponding difference with your script.

+15
source share

I modified the code a bit to just check out the main idea in the directory containing my perl programs, and it seems to work. You should iterate through @docs instead of @dir (and I highly recommend using both strict and warning 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 "$_"; } } 
+4
source share

glob does what you want without opening / closing. And as soon as you insert a group of files into @ARGV , the brilliant operator works as usual.

 @ARGV = <$indirname/*.txt>; while ( <> ) { ... } 
+1
source share

All Articles