In order to be able to return back to the top of the hash, you have to include the top reference to the arguments.
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
sub insert {
my ($top, $ref, $head, @tail) = @_;
return unless @tail;
if ('break' eq $head) {
insert($top, $top, @tail);
} else {
# Don't overwrite existing paths.
$ref->{$head} = {} unless exists $ref->{$head};
insert($top, $ref->{$head}, @tail);
}
}
my %hash;
while (<DATA>) {
chomp;
# Add a dummy end not to throw the last entry away.
insert(\%hash, \%hash, split(m=/=), '/.');
}
print "\nDump\n", Dumper(\%hash);
__DATA__
f1/f2/f3/f4/break/f1/f2/f5/break/f1/f2/f6
See also Data::Diver.
Update: Data::Diver example added.
while (<DATA>) {
chomp;
for my $path (split m=/break/=) {
DiveVal(\%hash, split m=/=, $path);
}
}
|