perl读取目录,写入文件

perl读取目录,写入文件

此脚本有两个输入参数,第一个参数为需要打印的文件目录,第二个参数为打印后的文件名;

该脚本名称为out_file_full_path

perl 复制代码
#!/bin/perl

use 5.010;
my $dir = $ARGV[0]; # 此为第一个参数;
opendir my $dh, $dir or die "Cannot open $dir: $!";

my $out_file = $ARGV[1]; # 此为第二个参数;
open OUT,">", $out_file or die "Cannot open $out_file:$!";

foreach $file (readdir $dh) {
  next if $file eq '.' or $file eq '..'; # 将当前目录.和上层目录..排除在打印列表之外
  my $full_dir = "$dir/$file"; #加上目录路径,若不需打印目录,则注释改行,修改下一行的$full_dir为$file即可
  print OUT $full_dir . "\n"; #将文件和目录写入OUT文件中,每行添加一个"\n",用于换行
  print "One file in $dir is $file\n"; #此行为debug 调试打印,可注释
}

closedir $dh; # 关闭打开文件夹的句柄
close OUT; #关闭打开文件的句柄

举例说明

perl 复制代码
# 现在在一个名为test的文件夹,test里面有3个文件,分别为test1.v,test2.v,test3.v
# 在终端中输入上述命令
[xxx@local]$ ./out_file_full_path test test.out

# 返回结果有两个,第一个即为打印在终端的:
One file in test is test1.v
One file in test is test2.v
One file in test is test3.v
# 第二个为,输出的文件,名称为test.out
# 在终端中使用cat命令获取文件内容
cat test.out
# 返回值为
$PATH/test/test1.v
$PATH/test/test2.v
$PATH/test/test3.v
# 其中$PATH为test所在路径
相关推荐
benchmark_cc1 小时前
一次获取多只股票实时行情:QuantDash `quotes.get(symbols=[...])` 批量快照
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
geovindu2 小时前
python: PCA
开发语言·后端·python·算法
__万波__2 小时前
嵌入式存储技术--1.Flash物理存储
java·开发语言
Chen_harmony3 小时前
十六、ALV树
开发语言·c++
qq_274475153 小时前
第 28 篇:Promise 全解析:状态、then/catch/finally、静态方法 all/race/allSettled/any
开发语言·javascript
西西弗Sisyphus3 小时前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - 初识回调(5)
开发语言·c++
程序员小杰@3 小时前
Java 统一报文转换 + 签名验签完整介绍
java·开发语言
Java后端的Ai之路5 小时前
Anthropic 官方文章《Building always-on agents》构建指南
开发语言·网络·python
船神丿男人5 小时前
从爬楼梯到最小路径和:6 道 C++ 动态规划题的状态设计
开发语言·c++·动态规划
Evand J5 小时前
【MATLAB例程】基于多基站AOA与距离辅助的二维运动目标定位及速度估计,附下载链接
开发语言·matlab·距离·aoa·多基站