How can I recursively read out directories in Perl?

前端 未结 6 2407
一生所求
一生所求 2021-02-14 06:08

I want to read out a directory recursively to print the data-structure in an HTML-Page with Template::Toolkit. But I\'m hanging in how to save the Paths and Files in a form that

6条回答
  •  梦毁少年i
    2021-02-14 06:21

    The answer by mdom explains how your initial attempt went astray. I would also suggest that you consider friendlier alternatives to File::Find. CPAN has several options. Here's one.

    use strict;
    use warnings;
    use File::Find::Rule;
    my @paths = File::Find::Rule->in(@ARGV);
    

    Also see here:

    • SO answer providing CPAN alternatives to File::Find.

    • SO question on directory iterators.

    And here is a rewrite of your recursive solution. Things to note: use strict; use warnings; and the use of a scoping block to create a static variable for the subroutine.

    use strict;
    use warnings;
    
    print $_, "\n" for dir_listing(@ARGV);
    
    {
        my @paths;
        sub dir_listing {
            my ($root) = @_;
            $root .= '/' unless $root =~ /\/$/;
            for my $f (glob "$root*"){
                push @paths, $f;
                dir_listing($f) if -d $f;
            }
            return @paths;
        }
    }
    

提交回复
热议问题