in reply to Reading from a flat text file database and storing contents in a hash

There are many different ways you could tackle this depending in large part how the configuration/data base file will be maintained. If you are writing a separate application to manage the file then you could use XML::Simple, Data::Dump::Streamer, a real data base using DBI and DBD::SQLite or a whole range of other options.

If your file format is XML or YAML there is a chance that it could be edited manually without breaking things, with YAML likely to be easier to get on with than XML.

Alternatively you could choose one of the plethora of configuration file formats (often Windows .ini style) and pick a module from CPAN to load it for you (there are many).

Or lastly, you could roll your own application specific file format and parse that. Code to do that using Perl is likely to be pretty small if you are even halfway smart about your file format and field separators.

The key question though is: hand edited or managed. Keep in mind that if you allow it to be hand edited, one day someone is going to screw it up.


DWIM is Perl's answer to Gödel
  • Comment on Re: Reading from a flat text file database and storing contents in a hash

Replies are listed 'Best First'.
Re^2: Reading from a flat text file database and storing contents in a hash
by wishartz (Beadle) on Apr 20, 2007 at 12:23 UTC
    Thanks for your help guys. In giving more thought to the problem, what I want to do is not hand edit the flat text file, but rather build an admin menu, so I can enter new services when needed. Also I wanted to get rid of the hash at the beginning of my program, which has the services in it and having to update it by hand. Instead I wanted to populate the hash with whatever is in the flat text file Does anybody know how I can do this?

      If the number of entries (for whatever definition of entry) is modest then using Data::Dump::Streamer is likely to be as good as anything. If you anticipate a large number of entries then it's probably worth finding out about DBI and the various DBD drivers that allow you to use a "real" data base.

      However, for the simple case consider:

      use strict; use warnings; use Data::Dump::Streamer; my %services = ( 1 => { name => "service1", host => { host1 => 1 }, }, 2 => { name => "service2", host => { host0 => 2, host5 => 2 }, }, ); Dump (\%services); open TEMP, '>', 'temp.txt'; print TEMP Dump (\%services)->Out (); close TEMP; my $newServices = do 'temp.txt'; Dump ($newServices);

      Prints:

      $HASH1 = { 1 => { host => { host1 => 1 }, name => 'service1' }, 2 => { host => { host0 => 2, host5 => 2 }, name => 'service2' } }; $HASH1 = { 1 => { host => { host1 => 1 }, name => 'service1' }, 2 => { host => { host0 => 2, host5 => 2 }, name => 'service2' } };

      DWIM is Perl's answer to Gödel
      I've just looked into XML::Simple as suggested and I can see how I can achieve what I wanted the program to do. Thanks guys.