Re: convert structured strings to possibly deep hash of hashes
- From: anno4000@xxxxxxxxxxxxxxxxxxxxxx
- Date: 9 Aug 2006 08:50:12 GMT
seven.reeds <seven.reeds@xxxxxxxxx> wrote in comp.lang.perl.misc:
Hi,
I have a list of well structured strings, actually they are file paths.
This just measn there are strings of '/' seperated sub-strings. I can
easily split these into an array. My question is really one of
building a HoH based on all of the string records. My goal is to take
strings like:
/file.txt
/a/file.txt
/a/b/c
/a/b/c/file.txt
/z/m/w/file.txt
and produce something like:
%dir_hash(
'file.txt' => '',
'a' => {
'file.txt' => '',
'b' => {
'c' => {
'file.txt'
}
}
},
'z' => {
'm' => {
'w' => {
'file.txt' => ''
}
}
}
)
Here is a recursive method:
my @files = qw(
/file.txt
/a/file.txt
/a/b/c
/a/b/c/file.txt
/z/m/w/file.txt
);
my %dir_hash;
for ( @files ) {
my ( @parts) = split m{/};
add_parts( \ %dir_hash, @parts);
}
print Dumper \ %dir_hash;
exit;
sub add_parts {
my ( $hash, $first, @parts) = @_;
$hash->{ $first} ||= {};
if ( @parts ) {
add_parts( $hash->{ $first}, @parts);
} else {
$hash->{ $first} = '';
}
}
It doesn't reproduce your structure exactly because all files are
given absolute path names. Therefore the root of the file system
is represented in the hash as a top node (which is an empty string).
Specify the files with relative path names (remove the leading "/"s)
to avoid that.
Anno
.
- References:
- convert structured strings to possibly deep hash of hashes
- From: seven.reeds
- convert structured strings to possibly deep hash of hashes
- Prev by Date: Re: Question about Arrays
- Next by Date: Re: perl editor
- Previous by thread: convert structured strings to possibly deep hash of hashes
- Next by thread: Re: convert structured strings to possibly deep hash of hashes
- Index(es):