in reply to directory listing to array tree

use strict; use warnings; use Data::Dumper qw( Dumper ); sub add { my $p = \shift; $p = \($$p->{$_}) for @_; } my $tree; while (<DATA>) { chomp; add $tree, m{[^/]+}g; } print(Dumper($tree)); __DATA__ /var/www/data/stuff /var/www /var/www/data/misc /var/logs /var/logs/data
$VAR1 = { 'var' => { 'www' => { 'data' => { 'misc' => undef, 'stuff' => undef } }, 'logs' => { 'data' => undef } } };

Golfed:

perl -MData::Dumper -ne'END{print Dumper$t}chomp;$p=\$t;$p=\($$p->{$_})for/[^\/]+/g'

Or if you don't mind a trailing blank line:

perl -MData::Dumper -nlE'END{say Dumper$t}$p=\$t;$p=\($$p->{$_})for/[^\/]+/g'

Replies are listed 'Best First'.
Re^2: directory listing to array tree
by contradev (Monk) on Sep 14, 2009 at 20:11 UTC
    Sorry guys, couldn't log in earlier.
    ++ikegami golf. I shall spend tomorrow trying to decypher it ; )

    Re: "show us 'yer code!" I was working backwards from the last node towards the root node but was hitting 20 lines+.
    The PHP was very similar to my perl attempt, which of course made me weep buckets.

    c
      Re: "show us 'yer code!" I was working backwards from the last node towards the root node but was hitting 20 lines+.

      Show your code anyway.

      #!/usr/bin/perl -- use strict; use warnings; use Tree::Builder; my $tb = Tree::Builder->new(); my @list = qw[ /var/www/data/stuff /var/www /var/www/data/misc /var/logs /var/logs/data ]; $tb->add($_) for @list; use Data::Dumper; print Dumper( { $tb->getTree } ); __END__ $VAR1 = { '' => { 'var' => { 'www' => { 'data' => { 'misc' => {}, 'stuff' => {} } }, 'logs' => { 'data' => {} } } } };