perl - 如何使用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;
解决方案
假设您有可以逐行读取的文件,因为目录名称表示日志文件:
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。
推荐阅读
- python - 过滤和排序列表提示问题 - Python3
- reactjs - 为什么即使添加 onChange 功能后我的输入字段也无法编辑 - 反应
- html - 修复内部资源管理器中的 CSS 阴影问题
- java - 为什么我不能将 apache.thrift 导入 IntelliJ 项目?
- lua - 我的 roblox gamepass gui 有问题
- c++ - 在 C++ 中定义纯虚方法有什么好处?
- javascript - 我正在尝试显示加密货币的信息
- linux - 如何使用 ffmpeg 分段 1080p 视频到 1080p、720p、360p ts 文件分段,每个分段中都有 index.m3u8 和主 m3u8 文件?
- php - 如何阅读下面的 Json 数据键和值个体?
- ios15 - 与 xcode 中的调试器失去连接