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所在路径
相关推荐
huohaiyu27 分钟前
Hashtable,HashMap,ConcurrentHashMap之间的区别
java·开发语言·多线程·哈希
Predestination王瀞潞5 小时前
IO操作(Num22)
开发语言·c++
宋恩淇要努力6 小时前
C++继承
开发语言·c++
沿着路走到底7 小时前
python 基础
开发语言·python
沐知全栈开发8 小时前
C# 委托(Delegate)
开发语言
任子菲阳8 小时前
学Java第三十四天-----抽象类和抽象方法
java·开发语言
csbysj20209 小时前
如何使用 XML Schema
开发语言
R6bandito_9 小时前
STM32中printf的重定向详解
开发语言·经验分享·stm32·单片机·嵌入式硬件·mcu
earthzhang20219 小时前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
杨枝甘露小码9 小时前
Python学习之基础篇
开发语言·python