我编写了一些perl代码来获取一些文件名并从文件中获取一些值。如果我从当前目录i执行我的perl脚本,e所有输入文件所在的目录,它正在执行正常并给我很好的结果。如果我将perl脚本更改为不同的目录,则表示无法打开该文件。这里有一小段代码。
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
my $opt_filepath;
&GetOptions (
"filepath:s" => \$opt_filepath,);
my $dir ="/home/priya/scripts/${opt_filepath}/check"; #base directory to look up for the files
print "$dir \n";
# Create output csv file
my $fileName = "Output.csv"; #output redirects to current directory
# ---- Read and Write as .csv file -------------------------
open (FILEHANDLER, ">", $fileName) or die("Could not write output File '$fileName' : $!");
print FILEHANDLER "Section,";
print FILEHANDLER "Result";
print FILEHANDLER "\n";
my @fileName = ();
my @FileContents = ();
my @Result = ();
opendir(DIR, $dir) or die "Unable to read Directory : $!";
while (my $file = readdir(DIR)) {
#Only files not subdirectories
next unless (-f "$dir/$file");
next unless ($file =~ m/^EXP_.*/i); #will search for all EXP files
print "$file \n";
@fileName = split(/_/, $file, 8);
print FILEHANDLER $fileName[1].",";
open (FH, "<", $file ) or die("Could not open Input File : $!");
@FileContents = <FH>;
@Result = grep (/^ADDSUB/, @FileContents);
print FILEHANDLER $FileContents[1]."\n";
close FH;
}
closedir(DIR);
close FILEHANDLER;
exit 0;
如果在我拥有所有输入EXP文件的目录中执行,它执行良好并给我很好的结果。如果我将代码复制到不同的目录并执行它会给我这个错误
>priyascript.pl -filepath test
/home/priya/scripts/test/check
EXPresult_101101_test
Could not open Input File : No such file or directory at priyascript.pl line 31
我打印$ file来检查它是否正在传递文件名。它传递文件名但不打开它。 我检查了所有文件夹权限并给出了777
请帮帮我
答案 0 :(得分:2)
您正在打开没有路径的输入文件。而不是
open (FH, "<", $file )
你应该
open (FH, "<", "$dir/$file" )