简体   繁体   English

读取perl中目录中的所有文件

[英]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 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 但是使用此代码,最后一个文件的最后一行不会被读取

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: 由于我不知道你在线阅读循环中做了什么,并且不理解@docs和@Dir,我将展示对我有用的代码:

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. 我稍微修改了代码,只是在包含我的perl程序的目录中测试基本思想,它似乎确实有效。 You should be iterating through @docs instead of @dir though (and I highly recommend using both the strict and warnings pragmas). 你应该迭代@docs而不是@dir(我强烈建议同时使用strict和warnings pragma)。

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. 如果没有打开/关闭的东西, glob会做你想要的。 And once you stick a group of files into @ARGV the "diamond" operator works as normal. 一旦你将一组文件粘贴到@ARGV ,“钻石”操作符就会正常工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM