当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - program is not executing from other directories in perl

问题描述:

I written some perl code to get some file names and get some values from files. If I execute my perl script from current directory i,e the directory all input files are located, it is executing fine and giving me fine results. If I change the perl script to different directory it saying could not open that file. here is small snippet of code.


#!/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;

if execute in the directory which i have all input EXP files, it is executing good and giving me good results. If i copy the code to different directory and execute it is giving me this error

>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

i printed $file to check whether it is passing the file name. It is passing the file name but not opening it.

I checked with all folder permissions and given 777

Please help me

网友答案:

You are opening the input file without a path. Instead of

open (FH, "<", $file )

you should have

open (FH, "<", "$dir/$file" )
分享给朋友:
您可能感兴趣的文章:
随机阅读: