in reply to Dynamically create the hash reference
#!/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); } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Dynamically create the hash reference
by k_manimuthu (Monk) on Oct 07, 2015 at 12:29 UTC |