in reply to Re^4: Dynamic population of a hash
in thread Dynamic population of a hash
Output is# Read in my list of paths and cut off the newlines my @list_of_paths = <DATA>; chomp @list_of_paths; my %hashed_path = (); for my $path_string (@list_of_paths) { # This tracks our descent in the path tree. We start at the top my $hpref = \%hashed_path; # Split the path into its component directories, and walk through th +em for my $dir (split m:/:, $path_string) { # At each level, if we've never been there before, create an entry + for it $hpref->{$dir} = {} unless exists $hpref->{$dir}; # Then descend into it so we're ready to insert the next level $hpref = $hpref->{$dir}; } } # See what the structure looks like use Data::Dumper; print Dumper \%hashed_path; __DATA__ /top/middle/bottom /top/middle/newleaf /top/new_middle/bottom
The topmost level has only the key of empty string because that's the first value in a split on '/' when the string starts with '/'.$VAR1 = { '' => { 'top' => { 'middle' => { 'newleaf' => {}, 'bottom' => {} }, 'new_middle' => { 'bottom' => {} } } } };
|
|---|