首页 > 解决方案 > 如何在 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'

我哪里错了或者这个脚本需要什么修改。

标签: perlfatal-error

解决方案


我将忽略 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

推荐阅读