【发布时间】:2012-08-04 12:58:53
【问题描述】:
我正在尝试开发一个 perl 脚本,它可以在用户的 所有 目录中查找特定文件名,而无需用户指定文件的完整路径名。
例如,假设感兴趣的文件是focus.qseq。它位于/home/path/directory/。在命令行中,通常用户必须指定文件的路径名才能访问它,例如:/home/path/directory/focus.qseq。
我希望用户只需在命令行中输入sample.qseq,然后perl 脚本就会自动将正确的文件分配给一个变量。如果文件是重复的但在不同的目录中,那么终端将显示这些文件的完整路径名,用户可以更好地指定他们想要的文件。
我阅读了有关 File::Find 模块的信息,但它并没有达到我想要的效果。
这是我实现上述代码的最佳尝试:
#!/usr/bin/perl
use strict; use warnings;
use File::Find;
my $file = shift;
# I want to search from the top down (you know, recursively) so first I look in the home directory
# I believe $ENV{HOME} is the same as $~/home/user
find(\&wanted, @$ENV{HOME});
open (FILEIN, $file) or die "couldn't open $file for read: $!\n";
我真的不明白wanted 子例程在这个模块中是如何工作的。如果有人知道实现我上面描述的代码的另一种方法,请随时提出建议。谢谢你
编辑: 如果我想使用命令行选项怎么办。像这样:
#!/usr/bin/perl
use strict; use warnings;
use File::Find;
use Getopt::Long qw(GetOptions);
my $file = '';
GetOptions('filename|f=s' => \$file);
# I believe $ENV{HOME} is the same as $~/home/user
find(\&wanted, @$ENV{HOME});
open (FILEIN, $file) or die "couldn't open $file for read: $!\n";
如何实现这个?
【问题讨论】:
标签: perl file directory user-input