Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

How to read every single file in a directory using foreach perl

im trying to make a script on reading all of the files inside a directory but it seems i cant.... the only thing i can is to list the names of the file inside the directory.So is there a way for me to list it ? (Kinda new to perl and 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
";}


exit;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you have files that can be read line-by-line, as the directory name indicates log files:

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
        }
    }
}

If you want to read directories recursively, perhaps switch over to Path::Tiny.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...