perl - 如何在 Perl 中按完整文件名从文件夹中读取文件
问题描述
我有一个 Perl 脚本,我在终端上给出了输入文件和输出文件的位置和名称
./R.pl <input file> <output file>
我正在尝试编写一个 Perl 程序,它可以将文件名作为输入并执行一些功能并在给定文件夹中生成输出。
这是我的 Perl 脚本:-
my $input_file = $ARGV[0]
or die "usage: $0 <input file> <output file>\n";
my $output_file = $ARGV[1]
or die "usage: $0 <input file> <output file>\n";
use File::Basename;
$fullspec = $ARGV[0];
my($files,$dir) = fileparse($fullspec);
print "Directory: " . $dir . "\n";
print "File:" . $files . "\n";
chomp($CEL_dir = $dir);
opendir (DIR, "$CEL_dir") or die "Couldn't open directory $CEL_dir";
$cel_files = $CEL_dir."/cel_files.txt";
open(CEL,">$cel_files")|| die "cannot open $file to write";
print CEL "cel_files\n";
use File::Find;
my @wanted_files;
find(
sub{
-f $_ && $_ =~ $files
&& push @wanted_files,$File::Find::name
}, "."
);
foreach(@wanted_files){
print CEL $CEL_dir."$_\n";
}close (CEL);
但它给出了错误: -
FATAL ERROR:Error opening cel file: /media/home/folder
/./44754.CEL
Read 2 cel files from: cel_files.txt
FATAL ERROR:Can't read file: '/media/home/folder
/./folder/44754.CEL'
我哪里错了或者这个脚本需要什么修改。
解决方案
我将忽略 OP 代码中似乎不必要的所有内容。
相反,我的答案集中在唯一似乎确实在做某事的部分:传递给find()
. 基于此,我确定 OP 想要搜索与命令行中给出的名称相同的文件,从当前目录开始。
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
my($match) = @ARGV;
die "usage: $0 <file name to match>\n"
unless defined $match;
# file search
find({
wanted => sub {
print "$File::Find::name\n"
if (-f $_) && ($_ eq $match);
},
},
'.'
);
exit 0;
示例用法:
$ ./R.pl some_file_name_to_find >cel_files.txt
问题仍然存在:为什么?同样可以在 shell 命令行上实现:
$ find . -type f -name some_file_name_to_find >cel_files.txt
推荐阅读
- python - 从xml中的元素中提取属性
- java - 从固定的快捷方式android中删除应用程序图标
- processmaker - 我正在寻找 Processmaker 4.0 的样品
- asynchronous - P4语言是异步编程吗?
- excel - 如何在 VBA 中打印特定的工作表?
- c++ - 为什么可以使用右值引用作为没有生命周期问题的成员?
- flutter - 如何在 Flutter 中扭曲图标按钮
- c - 初始化大小为 2 的数组是否与分配大小为 2 的数组的指针相同?
- angular - 如何在 Angular 11 / Rxjs 中等待更新时保留可观察异步管道数组的最后一个值
- node.js - 我的反应角色代码不起作用 Discord.JS