http://www.perlmonks.org?node_id=889649


in reply to Alternative for a directory builder

I used the same idea, but File::Spec to parse the filename/directory portions when I was testing the following, which may help if you need portability later:

use strict; use warnings; use File::Spec; my $p = q{/var/www/vhosts/testing.com/httpdocs/test1.html}; my ( $v, $d, $f ) = File::Spec->splitpath( $p ); my @dp = File::Spec->splitdir( $d ); foreach my $i ( 0 .. $#dp ) { next unless ( $i and length $dp[$i] ); print File::Spec->catdir( @dp[0 .. $i ] ), qq{\n}; }

For my sample data, the code gave me the following output:

/var /var/www /var/www/vhosts /var/www/vhosts/testing.com /var/www/vhosts/testing.com/httpdocs

Hope that helps.

Update 2011-02-22

I was able to come up with a map solution that seemed to work, although I believe others may have better solutions:

use strict; use warnings; use File::Spec; my $p = q{/var/www/vhosts/testing.com/httpdocs/test1.html}; my ( $v, $d, $f ) = File::Spec->splitpath( $p ); my @dp = File::Spec->splitdir( $d ); print join( qq{\n}, map{ if (! defined $dq ) { $dq = q{/}; } $dq .= $_ . q{/}; } grep{ m/.+/; } @dp ), qq{\n};

or, the following:

use strict; use warnings; use File::Spec; my $p = q{/var/www/vhosts/testing.com/httpdocs/test1.html}; my ( $v, $d, $f ) = File::Spec->splitpath( $p ); my @dp = File::Spec->splitdir( $d ); print join( qq{\n}, map{ File::Spec->catdir( @dp[0 .. $_] ) } grep{ length $dp[$_]; } 0 .. $#dp ), qq{\n};