开发者

How do I search for a particular file in a directory using Perl?

I have a file in a directory and i want to pick one particular file from the directory at a time.

Code is given below:

$xml_file_name = <STDIN>;
chomp ($xml_file_name);

@o = file_search($xml_file_name);
print "file::@o\n";

sub file_search
{
    opendir (DIR, "/home/sait11/Desktop/test/Test cases") or die "Failed to open directory\n";
    @dirs_found = grep { /$xml_file_name/ } readdir DIR;
    closedir (DIR);
#   print "dir ::@dirs_found\n";
    return @dirs_found;
}

I am inputting the file name to be re开发者_StackOverflow社区turned as sample.xml. But in the @dirs_found variable, all the file names that starts with 's' are getting stored.

How to find out the exact one file at a time?


To find a specific file, simply open the file, or run a file test on it:

my $file = "/home/sait11/Desktop/test/Test cases/$xml_file_name";

print "$file found\n" if -f $file;

Running your code, it certainly seems to work. If you enter a pattern, then it correctly picks up the file names from the target directory that match that Perl regex you type in. What name were you looking for?

If you revise the grep to read:

my @dirs_found = grep { /^$xml_file_name$/ } readdir DIR;

then it will exclude values where the regex doesn't match the entire name. On the other hand, you give up some flexibility when you do that.


Got the answer, i have to give the entire file name, so that it matches that particular file only.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜