I'm quite new to Perl and I'm trying to build a hash recursively and getting nowhere. I tried searching for tutorials to dynamically build hashes, but all I could find were introductory articles about hashes. I would be grateful if you point me towards the right direction or suggest a nice article/tutorial.
I'm trying to read from a file which has paths in the form of
one/two/three
four
five/six/seven/eight
and I want to build a hash like
VAR = {
one : {
two : {
three : ""
}
}
four : ""
five : {
six : {
seven : {
eight : ""
}
}
}
}
The script I'm using currently is :
my $finalhash = {};
my @input = <>;
sub constructHash {
my ($hashrf, $line) = @_;
@elements = split(///, $line);
if(@elements > 1) {
$hashrf->{shift @elements} = constructHash($hashrf->{$elements[0]}, @elements );
} else {
$hashrf->{shift @elements} = "";
}
return $hashrf;
}
foreach $lines (@input) {
$finalhash = constructHash($finalhash, $lines);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…