tags:

views:

62

answers:

2

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 returned 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?

+6  A: 

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.

Jonathan Leffler
A: 

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

Senthil kumar
huh? You know the full path already? If so, you dont have to search, just use -f $file as @Jonathan suggested
Øyvind Skaar