tags:

views:

75

answers:

4

I have a piece of Perl code for searchnig a directory and display the contents of that directory, if match is found. The code is given below:

$test_case_directory = "/home/sait11/Desktop/SaLT/Data_Base/Test_Case";
$xml_file_name = "sample.xml"

$file_search_return = file_search($xml_file_name);
print "file search return::$file_search_return\n";


sub file_search
{
    opendir (DIR, $test_case_directory) or die "\n\tFailed to open directory that contains the test case xml files\n\n";

    print "xml_file_name in sub routines:: $xml_file_name\n";

    $dirs_found = grep { /^$xml_file_name/i } readdir DIR;
    print "Files in the directory are dirs_found :: $dirs_found\n";
    closedir (DIR);
    return $dirs_found;
}

Output is,

xml_file_name in sub routines:: sample.xml
Files in the directory are dirs_found :: 1
file search return::1

It is not returning the file name found. Instead it returns the number 1 always.

I don't know why it is not returning the file name called sample.xml present in the directory.

+2  A: 

you should say @dirs_found, not $dirs_found

Habbie
+8  A: 

perldoc grep says:

In scalar context, returns the number of times the expression was true.

And that's exactly what you are doing. So you found 1 file and that result is assigned to $dirs_found variable.

n0rd
+3  A: 
($dirs_found) = grep { /^$xml_file_name/i } readdir DIR; #capture it
Nikhil Jain
this works perfectly ... thanks
Senthil kumar
+3  A: 

Why are you opening a directory and looking for a particular filename? If you want to see if the file is there, just test for it directly:

 use File::Spec::Functions;
 my $file = catfile( $test_case_directory, $xml_file_name );
 if( -e $file ) { ... }

When you run into these sorts of problems, though, check the result at each step to check what you are getting. Your first step would decompose the problem statement:

 my @files = readdir DIR;
 print "Files are [@files]\n";

 my $filtered = grep { ... } @files;
 print "Files are [$filtered]\n";

Once you do that you see that the problem is grep. Once you know that the problem is grep, you read its documentation, notice that you are using it wrong, and you're done sooner than it would take to post a question on StackOverflow. :)

brian d foy