in reply to property file parsing

This works by recursively constructing branches of the tree top-down and works with arbitrary "deep" keys:
use strict; use warnings; use Data::Dumper; my %properties; while (my $propline = <DATA>) { next if $propline =~ /^#/; chomp $propline; my ($key, $value) = split(/=/, $propline, 2); _insert(\%properties, $key, $value); } sub _insert { my ($root, $key, $value) = @_; my ($first, $rest) = split /\./, $key, 2; if (defined $rest) { $root->{$first} = {} unless ref($root->{$first}) eq 'HASH'; _insert($root->{$first}, $rest, $value); } else { $root->{$first} = $value; } } print Dumper(\%properties); __DATA__
language_id.en_US=-1 language_id.es_US=-11 language_id.en_CA=-12 language_id.fr_CA=-13 langid.SPMEX=es_US langid.FRCAN=fr_CA altlang.US=SPMEX altlang.CA=FRCAN itemattr.newpart.seq=1 itemattr.newpart.name=New Part itemattr.newpart.image1.en_US=newitem_icon.gif itemattr.newpart.image1.es_US=newitem_icon_sp.gif itemattr.newpart.image1.en_CA=newitem_icon.gif itemattr.newpart.image1.fr_CA=newitem_icon_fr.gif itemattr.watersaver.seq=2 itemattr.watersaver.name=New Part itemattr.watersaver.image1.en_US=newitem_icon.gif itemattr.watersaver.image1.es_US=newitem_icon_sp.gif itemattr.watersaver.image1.en_CA=newitem_icon.gif itemattr.watersaver.image1.fr_CA=newitem_icon_fr.gif

Replies are listed 'Best First'.
Re^2: property file parsing
by rhesa (Vicar) on Feb 03, 2006 at 22:15 UTC
    No need for recursion if a simple loop suffices:
    my ( $first, @subkeys ) = split /\./, $key; my $last = pop @subkeys; my $ref = $properties{$first} ||= {}; $ref = $ref->{$_} ||= {} for(@subkeys); $ref->{$last} = $value;

      Yeah, _insert is even tail recursive, so making a loop from it is no big deal. But, believe it or not, those recursive solutions just come more easily to me.

      BTW, your snippet fails to overwrite previously set to "True" scalar values. There is no case of this in the OP data sample. But this kind of anomaly is clobbered the same way by OP's script and mine.
      So you can even argue, that your algorithm crashing on such data is a feature :)

        Good point! I would also consider it a feature. I'd say it would be a syntax error in the config file, and I'd throw an exception for that if it happened.
      perfect! thankyou.