搜索目录并以散列形式存储

时间:2014-02-18 04:27:08

标签: perl hash subdirectory

从用户的输入,我应该能够搜索其子目录,直到名为“list”的固定目录。问题是如何将路径存储到哈希中,以便我可以检索数据并在之后显示它。

我的目录树:

                        ->blue    -->Aug21   --->projA  ---->list   ----->name
/tmp/general/place/brand->red     -->Jan03
                        ->yellow  -->June22  --->projB  ---->list

directory.pl:

use strict;
use warnings;

print "Searching Directory...\n";
&search_dir('/tmp/general/place/brand'); #could be 'tmp/general/place/brand/blue/Aug21'
my ($input,$tt,$str,$fn,@pp,@cap);

sub search_dir{
$input=shift;
opendir DH,$input or die"$!";
while($_=readdir(DH)){
    next if $_ eq "." or $_ eq "..";
    if ($_ eq "list"){
        $fn = $input.'/'.$_;
        push @pp, $fn;
        return;
        }
    else{
        $fn = $input.'/'.$_;
        }

    if(-d $fn){
        push @cap,$fn;
        }
}

if(scalar @cap == 0){
    return;
    }
foreach (@cap){
    &search_dir($_) ;
    }
}

if (@pp){
    print "Located directory...\n";
    foreach $tt (@pp){
            $str='/tmp/general/place/brand';
            $tt=~ s/$str//g;
            print $tt,"\n";
    #Hash?  $file{$color}{$date}{$quantity}{$list}= split (/\//,$tt);
    }
}
else {
     print "Could not locate directory\n";
    }

预期产出:

Searching Directory...
Located Directory...
/blue/Aug21/projA/list
/yellow/June22/projB/list
Info  :1
Color :blue
Date  :Aug21
Project :projA
Info  :2
Color :yellow
Date  :June22
Project:projB

1 个答案:

答案 0 :(得分:1)

在linux下,使用find可能更容易。快速而肮脏,但它会完成这项工作。

my @dirs = `/usr/bin/find -name "/tmp/general/place/brand/" -type d`;
chomp(@dirs);
my $data = {};
foreach my $dir (@dirs){
  my @path = split(/\//,$dir);
  #you have found a list in the right depth
  if (scalar(@path) >= 7 && $path[7] eq 'list'){
    $dir =~ s!/tmp/general/place/brand!!is;
    print "Found $dir\n";
    print "Color :".$path[4];
    ...
  }
}