首页 > 解决方案 > 如何使用foreach perl读取目录中的每个文件

问题描述

我试图制作一个脚本来读取目录中的所有文件,但似乎我不能....我唯一能做的就是列出目录中文件的名称。所以有没有办法让我列出它 ?(对 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;

标签: perl

解决方案


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

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


推荐阅读