如何使用 Perl 在目录中搜索特定文件? [英] How do I search for a particular file in a directory using Perl?

查看:92
本文介绍了如何使用 Perl 在目录中搜索特定文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在目录中有一个文件,我想一次从目录中选择一个特定的文件.

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

代码如下:

$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;
}

我正在输入要作为 sample.xml 返回的文件名.但是在 @dirs_found 变量中,所有以 's' 开头的文件名都会被存储.

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?

推荐答案

要查找特定文件,只需打开该文件,或对其运行文件测试:

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;

运行您的代码,它似乎确实有效.如果您输入一个模式,那么它会从目标目录中正确选择与您键入的 Perl 正则表达式匹配的文件名.您要查找什么名称?

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?

如果将grep修改为:

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.

这篇关于如何使用 Perl 在目录中搜索特定文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆