How can I recursively read out directories in Perl?

前端 未结 6 2408
一生所求
一生所求 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条回答
  •  死守一世寂寞
    2021-02-14 06:26

    You should always use strict and warnings to help you debug your code. Perl would have warned you for example that @files is not declared. But the real problem with your function is that you declare a lexical variable @paths on every recursive call to list_dirs and don't push the return value back after the recursion step.

    push @paths, list_dir($eachFile)
    

    If you don't want to install additional modules, the following solution should probably help you:

    use strict;
    use warnings;
    use File::Find qw(find);
    
    sub list_dirs {
            my @dirs = @_;
            my @files;
            find({ wanted => sub { push @files, $_ } , no_chdir => 1 }, @dirs);
            return @files;
    }
    

提交回复
热议问题