The following code is a slightly more robust version. Note in particular that the result of the open is checked and a three parameter open is used. Note too that the line gets chomped and the format checked (at least a little) and bad input lines rejected. Even then a lot more checking ought to be done (duplicate keys anyone?).
I'd recommend however that you look at some of the configuration options bobf mentioned.
#!/usr/bin/perl use strict; use warnings; my %data; #open INPUT, '<', $InputFile" or die "Failed to open $InputFile: $!"; while (<DATA>) { chomp; next if ! /(\w+)\s*:\s*(\w+)/; $data{$1} = $2; } print "$_ => $data{$_}\n" for keys %data; __DATA__ foo:FOO bar:BAR bogus data line - comment maybe? baz:BAZ qux:QUX
Prints:
bar => BAR baz => BAZ qux => QUX foo => FOO
In reply to Re: Converting a Flat-File to a Hash
by GrandFather
in thread Converting a Flat-File to a Hash
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |