如何使用foreach perl读取目录中的每个文件

时间:2019-08-05 01:41:34

标签: perl

我试图制作一个脚本来读取目录中的所有文件,但看来我做不到...。我唯一能做的就是列出目录中文件的名称。我列出来吗? (Kinda是Perl和linux的新手:U)

#!/usr/bin/perl

use strict;
use warnings;

#locate directories

my $DIR = "/home/aimanhalim/LOG";
opendir(DIR, $DIR) or die $!;

#open Directory and read all the file.

while (my $DIR = readdir(DIR)) {print "$DIR\n";}


exit;

1 个答案:

答案 0 :(得分:1)

假设您具有可以逐行读取的文件,因为目录名指示日志文件:

use strict;
use warnings;
use autodie;

my $DIR = '/home/aimanhalim/LOG';
chdir $DIR;
opendir my $dh, $DIR;
while (my $entry = readdir $dh) {
    next if $entry =~ /^[.]/; # skip the '.' and '..' entries and hidden files
    if (-f $entry) { # skip entries that are not files
        open my $fh, '<', $entry;
        while (my $line = $fh->getline) {
            # do something with the content
        }
    }
}

如果您要递归读取目录,则可以切换到Path::Tiny