in reply to split string into hash of hashes...
Update: Working this out for myself demonstrated to me that this is just a clunky version of Rolf's more elegant code, above. But it makes each operation more clear to my less expert eyes.
Time flies like an arrow. Fruit flies like a banana.
This is a case where autovivification and hashrefs are your friends. With a helping hand from some creative data structure manipulation.
You have two issues:
- how to create a hash of hashes without knowing the depth of the structure in advance.
- How to include a value for the entire dimension three levels from the bottom, knowing, as others have pointed out, that an element cannot contain at once a value and a reference to the lower levels of the structure.
Output:#!/usr/local/bin/perl use strict; use warnings; use Data::Dumper; $Data::Dumper::Sortkeys = 1; print "Content-type:text/html\n\n"; my $line1 = 'HKEY_LOCAL_MACHINE\SOFTWARE\Vendor\Product\CurrentVersion +\Tokens\Encotone\SerialNumberUserAttribute=12345'; my $line2 = 'LanMan:= ; REG_SZ'; my @line1_parts = split(/[=\\]/, $line1); my @line2_parts = split(/:= ;/, $line2); my %hash; my $href = {}; my $i; for $i (0 .. $#line1_parts) { if ($i == 0) { # for the first time around, create the first level of the str +ucture, itself as a hash. Autovivification means that simply referri +ng to it creates it. No need to put anything in it yet. $hash{$line1_parts[$i]} = {}; #create a hash reference to that element (which is itself a ha +sh); $href = \%{ $hash{$line1_parts[$i]} }; } elsif ($i == $#line1_parts) { # last time around, create the acutal hash elements you want, +filling in down to the bottom level with dummy elements for the Seria +lNumberUserAttribute. $href->{'dummy'} = $line1_parts[$i]; $href->{$line2_parts[0]}{'Value'}=""; $href->{$line2_parts[0]}{'Type'}=$line2_parts[1]; } else { # each next time around, create the next level of the structur +e, itself as a hash, tacked onto the hash that the hash ref points to $href->{ $line1_parts[$i] } = {}; # move the hash ref to this new hash $href = \%{ $href->{$line1_parts[$i]} }; } } print "<pre>\n"; print Dumper(\%hash); print "</pre>\n";
$VAR1 = { 'HKEY_LOCAL_MACHINE' => { 'SOFTWARE' => { 'Vendor' => { 'Product' => { 'CurrentVersion' => { 'Tokens' => { 'Encotone' => { 'SerialNumberUserAttribute' => { 'LanMan' => { 'Type' => ' REG_SZ', 'Value' => '' }, 'dummy' => '12345' } } } } } } } }
Time flies like an arrow. Fruit flies like a banana.
|
---|
In Section
Seekers of Perl Wisdom