Everyone knows how to walk a directory tree and collect the file paths into a flat list, perhaps filtering them along the way.

However, I want to collect those paths into a tree of hashes, where keys would be file or subdirectory names and values would be a scalar for a file and a hashref for a subdirectory.
Once in a tree, I could apply recursive programs to do whatever I need with my files.

Here is my first try, with sample output (and a directory browser in 3 lines of perl :-).

#! perl -w use strict; use File::Find; my $dirth = dirTreeHash(shift); sub dirTreeHash { my $dir = shift; return unless defined $dir && -d $dir; $dir =~ s#\\#/#g; # Win32 :-( my $dirth = {}; find sub { return if -d; eval join '', '$dirth->', ( map { '{\'' . $_ . '\'}' } split +'/', $File::Find::name ), '=""'; warn $@ if $@; }, $dir; $dirth; } # dump it use Data::Dumper; $Data::Dumper::Indent = 1; print Dumper $dirth; # browse it use Tk::ObjScanner; MainWindow->new->ObjScanner(caller => $dirth)->pack; + Tk::MainLoop; __END__ H:\devperl\perlmonks\TryDirTreeHash.pl H:\devperl\PerlMonksChat2 $VAR1 = { 'H:' => { 'devperl' => { 'PerlMonksChat2' => { 'README' => '', 'ChangeLog' => '', 'Makefile' => '', 'getchat.pl' => '', 'getpage.pl' => '', 'getchat.old.pl' => '', 'test' => { 'testnn.pl' => '', 'nodetypes' => '' }, 'PerlMonks' => { 'Users.pm' => '', 'NewestNodes.pm' => '', 'Chat.pm' => '' }, 'Noname6.pl' => '', 'PerlMonks.pm' => '', 'pmpager.pl' => '', 'PerlMonksChat.pm' => '', 'pmchat' => '' } } } };
Question:
What other/better ways to perform this dir-to-hash mapping would you suggest?

Rudif

In reply to How to map a directory tree to a perl hash tree by Rudif

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.