If you don't feel like using the Tree module, you can build your data structure by temporarily storing the references to each hash in a separate hash, as follows.
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
This code generates the following dump of %data:
$VAR1 = {
'a' => {
'c' => {
'e' => {},
'f' => {}
},
'b' => {
'd' => {}
}
}
};
I'm not sure what you mean by
I have no idea how to store this either.
. If your looking for a way to save and load data to disk, you can use Data::Dumper and 'do' as follows.
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;
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.)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.