开发者

Why do I get a number instead a list of filenames from readdir?

开发者 https://www.devze.com 2023-01-19 14:21 出处:网络
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:

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/sai开发者_如何学Got11/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.


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.


($dirs_found) = grep { /^$xml_file_name/i } readdir DIR; #capture it

Problem was that, you were evaluating the grep as scalar context, change it to list context will give you the desired result.

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

In list context, it returns the elements for which the expression was true.


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. :)


you should say @dirs_found, not $dirs_found

0

精彩评论

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