[ACCEPTED]-How do I load a file into a Perl hash?-hash

Accepted answer
Score: 22

Here you go:

my %hash;
while (<FILE>)
   my ($key, $val) = split /=/;
   $hash{$key} .= exists $hash{$key} ? ",$val" : $val;

This walks through every line 3 splitting on the '=' sign and either adds 2 an entry or appends to an existing entry 1 in the hash table.

Score: 5

If you have control over the data file, consider 11 switching from a custom format to something 10 like YAML. This gives you a lot of power 9 out of the box without having to hack your 8 custom format more and more. In particular, multiple 7 keys creating a list is non-obvious. YAML's 6 way of doing it is much clearer.

name:       Wally Jones
department: [foo, bar]
location:   [baz, biff]

Note also 5 that YAML allows you to sculpt the key/value 4 pairs so they line up for easier reading.

And 3 the code to parse it is done by a module, YAML::XS being 2 the best of the bunch.

use File::Slurp;
use YAML::XS;
use Data::Dumper;

print Dumper Load scalar read_file(shift);

And the data structure 1 looks like so:

$VAR1 = {
          'department' => [
          'location' => [
          'name' => 'Wally Jones'

More Related questions