[ACCEPTED]-Read all files in a directory in perl-file

Accepted answer
Score: 16

As I don't know what you are doing in the 4 line reading loop and don't understand @docs 3 and @Dir, I'll show code that 'works' for 2 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 1 difference to your script.

Score: 5

I modified the code slightly to just test 5 the basic idea in a directory containing 4 my perl programs and it does seem to work. You 3 should be iterating through @docs instead 2 of @dir though (and I highly recommend using 1 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 "$_";
    }
}
Score: 1

glob does what you want, without the open/close 3 stuff. And once you stick a group of files 2 into @ARGV the "diamond" operator works 1 as normal.

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

More Related questions