我有一个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'
在那里我错了还是什么修改需要在这个脚本。
我会忽略所有的,这似乎是不必要的操作码的东西。
相反,我的回答集中在实际上似乎并做一些事情只有一件:传递给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
现在的问题是:为什么?同样可以与外壳命令行来实现:
$ find . -type f -name some_file_name_to_find >cel_files.txt
除去$ CEL_dir后,按预期工作
use File::Find;
my @wanted_files;
find(
sub{
-f $_ && $_ =~ $files
&& push @wanted_files,$File::Find::name
},"$ARGV[0]"
);
foreach(@wanted_files){
print CEL "$_\n"; # remove $CEL_dir
}close (CEL);