1. 程式人生 > >多程序遍歷目錄並查詢檔案

多程序遍歷目錄並查詢檔案

有時候需要在一個深層次的目錄下面查詢某個型別的檔案,這裡利用遍歷遞迴查詢目錄,並使用多程序操作提高效率。

如果現在只需要在一個目錄下查詢,指令碼getfile_single.pl為:

use strict;
my @ARGV==2||die"usage:*.pl dir rec\n";
my $dir=$ARGV[0];##input directory
my $logfile=$ARGV[1];##result file to save path
my @all;
my $str;
my $grep = "";###this is the regular exression to match the file expected
open(FILE,">$logfile")||die"can't write the file:$!\n"; ::ErgodicDirToGetFile($dir); close(FILE); sub ::ErgodicDirToGetFile { my ($dir) = @_; if(-d $dir) { opendir(DIRHANDLE,$dir); my @dirs = grep(!/^\.\.?$/,readdir(DIRHANDLE));##delete the element "." and ".." closedir
(DIRHANDLE); } foreach my $str(@dirs) { if(-d "$dir\\$str") { ::ErgodicDirToGetFile("$dir\\$str"); } else { my $temp = "$dir\\$str"; if($temp =~/$grep/) { print FILE "$temp\n"; } } } }

如果有多個目錄,或許多程序可以提升查詢效率:

use strict;
my @all;
my $str;
my @pid;
my $i;
open(FILE,"dir.list")||die"can't open the file:$!\n";##dir.list is the file include all the directory you want to search for your desire file
@all=<FILE>;
chomp(@all);
close(FILE);

for($i=0; $i<@all; $i++)
{
    $str = $all[$i];
    defined($pid[$i]=fork())||die"can't fork\n";
    if($pid[$i]==0)##sub process begin
    {
        my $cmd = "perl getfilepath_single.pl $str result_$i.scp";##result_$i.scp is the result file to save path
        print "$cmd\n";
        system($cmd);
        exit(0);
    }
}
for($i=0; $i<@all; $i++)
{
    waitpid($pid[$i],0);
}