manav_gupta has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, So I have a flat file like so:

AMGR.HOSTA.CORBA_PORT=0
AMGR.HOSTA.EXECUTABLE_FILENAME=/opt/datachannel/bin/visual
AMGR.HOSTA.ROOT_DIRECTORY=/opt/datachannel/
BCOL.1.2.3002_SERVICE_PORT=0
BCOL.1.2.COLLECTOR_ALIAS=2
CATCHALL=OrderedCollection ()
I need to read that file and build a tree-like hash. what would be most elegant way of doing that, without having to search/parse for each period-delimited word?
  • Comment on read flat file and build tree-like structure

Replies are listed 'Best First'.
Re: read flat file and build tree-like structure
by ikegami (Patriarch) on Nov 19, 2007 at 17:03 UTC
    Parsing is simply using split twice. Data::Diver provides an easy means of storing the data in the appropriate place in the hash.
    use Data::Diver qw( DiveVal ); my %hash; while (<>) { chomp; my ($key, $val) = split(/=/, $_, 2); my @keys = split(/\./, $key); DiveVal(\%hash, map \$_, @keys) = $val; }
Re: read flat file and build tree-like structure
by pc88mxer (Vicar) on Nov 19, 2007 at 17:00 UTC
    Untested, but should work:

    sloppy coding removed

    Okay - I've learned my lesson to test before posting.

      Close. Keep track of a reference to the reference.

      my %hash; while (<>) { chomp; my ($key, $val) = split(/=/, $_, 2); my @elts = split(/\./, $key); my $p = \\%hash; $p = \( ${$p}->{$_} ) for @elts; $$p = $val; } use Data::Dumper; print Dumper(\%hash);

      Tested.

        Wow, that's awesome. I'd been wondering for last few hours on the best way of doing it... thank you so much!
      Okay - the above should work now.
        Umm... it gives you that button to "update"?
Re: read flat file and build tree-like structure
by salva (Canon) on Nov 20, 2007 at 09:01 UTC
    use Config::Properties::Simple; my $cfg = Config::Properties::Simple->new(file => '/my/file.cfg') or d +ie "unable to open config file"; my $tree = $cfg->splitToTree;