[ACCEPTED]-How do I load a file into a Perl hash?-hash
Here you go:
my %hash;
while (<FILE>)
{
chomp;
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.
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' => [
'foo',
'bar'
],
'location' => [
'baz',
'biff'
],
'name' => 'Wally Jones'
};
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.