in reply to how to construct tree from parent pointer list
This code generates the following dump of %data:use strict; use Data::Dumper; my %data; { my %temp; while (<DATA>) { chomp; /^(.*?):(.*?)$/; my $key = $2; my $value = $1; if (!defined $temp{$key}) { $temp{$key} = {}; $data{$key} = \%{$temp{$key}}; }; $temp{$key}{$value} = \%{$temp{$value}}; }; } print Dumper \%data; __DATA__ b:a c:a d:b e:c f:c
$VAR1 = { 'a' => { 'c' => { 'e' => {}, 'f' => {} }, 'b' => { 'd' => {} } } };
Be aware though that saving and loading hashes this way can be a security risk if your script and saved file have different read/write permissions for different users. (i.e. If security is set up in such a way that a user is unable to edit the Perl script, but is able to edit save.out, this would introduce a way for that user to execute code in the Perl script.)use strict; use Data::Dumper; my %saved = ( 'test1' => { 'test2' => 'b' }, 'b' => [1,2,3,4], 'test3' => 'x' ); print "Constructed hash\n"; print Dumper \%saved; open FILE, ">save.out"; print FILE Dumper \%saved; close FILE; my %loaded = %{do 'save.out'}; print "Loaded hash\n"; print Dumper \%loaded;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: how to construct tree from parent pointer list
by nothingmuch (Priest) on Mar 22, 2006 at 09:56 UTC | |
by BerntB (Deacon) on Mar 22, 2006 at 11:31 UTC | |
by nothingmuch (Priest) on Mar 22, 2006 at 23:36 UTC |