在Path-Class-Dir模块中创建目录树

时间:2012-05-14 22:10:58

标签: perl module directory traversal

Path::Class模块是评分最高的模块,在cpan.org上非常好reviews。我想知道Path::Class:Dir模块是否可以像这样创建目录树*:

/home/scottie/perl/lib/Path-Class-0.25
  -> lib/
     -> Path/
        -> Class/
           -> Dir.pm
           -> Entity.pl
           -> File.pl
        -> Class.pl
  -> t/
     -> 01-basic.t
     -> 02-foreign.t
     -> 03-filesystem.t
     -> 04-subclass.t
     -> 05-traverse.t
     -> author-critic.t
  -> Build.PL
  -> Changes
  -> dist.ini
  -> INSTALL
  -> LICENSE
  -> Makefile.PL
  -> MANIFEST
  -> META.yml
  -> README
  -> SIGNATURE

*)来源:Path-Class-0.25.tar.gz文件和字符串指示目录末尾的“/”(如* nix系统中的ls -p

这样(来自root的完整路径):

  /home/scottie/perl/lib/Path-Class-0.25
  -> /home/scottie/perl/lib/Path-Class-0.25/lib/
     -> /home/scottie/perl/lib/Path-Class-0.25/lib/Path/
        -> /home/scottie/perl/lib/Path-Class-0.25/lib/Path/Class/
           -> /home/scottie/perl/lib/Path-Class-0.25/lib/Path/Class/Dir.pm
           -> /home/scottie/perl/lib/Path-Class-0.25/lib/Path/Class/Entity.pl
           -> /home/scottie/perl/lib/Path-Class-0.25/lib/Path/Class/File.pl
        -> /home/scottie/perl/lib/Path-Class-0.25/lib/Path/Class.pl
  -> /home/scottie/perl/lib/Path-Class-0.25/t/
     -> /home/scottie/perl/lib/Path-Class-0.25/t/01-basic.t
     -> /home/scottie/perl/lib/Path-Class-0.25/t/02-foreign.t
     -> /home/scottie/perl/lib/Path-Class-0.25/t/03-filesystem.t
     -> /home/scottie/perl/lib/Path-Class-0.25/t/04-subclass.t
     -> /home/scottie/perl/lib/Path-Class-0.25/t/05-traverse.t
     -> /home/scottie/perl/lib/Path-Class-0.25/t/author-critic.t
  -> /home/scottie/perl/lib/Path-Class-0.25/Build.PL
  -> /home/scottie/perl/lib/Path-Class-0.25/Changes
  -> /home/scottie/perl/lib/Path-Class-0.25/dist.ini
  -> /home/scottie/perl/lib/Path-Class-0.25/INSTALL
  -> /home/scottie/perl/lib/Path-Class-0.25/LICENSE
  -> /home/scottie/perl/lib/Path-Class-0.25/Makefile.PL
  -> /home/scottie/perl/lib/Path-Class-0.25/MANIFEST
  -> /home/scottie/perl/lib/Path-Class-0.25/META.yml
  -> /home/scottie/perl/lib/Path-Class-0.25/README
  -> /home/scottie/perl/lib/Path-Class-0.25/SIGNATURE

我试图这样做,但我的代码有问题:

#------------------8<------------------
my $dir = Path::Class::Dir->new('/home/scottie/perl/lib/Path-Class-0.25');

my $nfiles = $dir->traverse(sub {
    my ($child, $cont) = @_;
    return if -l $child; # don't follow symlinks

    #print Dumper($child);
    #print "$child\n";

    print $child->{'dir'}{'dirs'}[-1];
    print " -> ";
    print $child->{'file'};
    print "\n";
    return $cont->();
});
#------------------8<------------------

您能不能对我的代码有所了解并告诉我如何在$child中制作没有完整路径的目录树?

非常感谢!

最好的问候,
斯科特

1 个答案:

答案 0 :(得分:4)

您需要使用basename的{​​{1}}方法(也可用作Class::Path::File的方法)来提取路径的最后一个元素。

您还必须使用回调参数来跟踪当前的缩进级别。

此计划似乎符合您的要求。

Class::Path::Dir