nospam said:
If I had a text file with the following
two columns:
key1 value1
key2 value2
key3 value3
How would I read in this file and create an
associative array?
-Thanks
Hi,
There are two solutions for this problem, and each one depends on the
kind of the file you are trying to read.
1. If your columns are not fixed-width, but are separated by some sort
of a delimiter ( A double space in your example ). Then you can use
this:
my @cols = split($delimiter, $line);
Where $delimiter is the column separator and $line is the line you
want to extract information from. This will give you the key in
$cols[0] and the value in $cols[1] where you can easily put them in a
hash. Note that you can use a regular expression in place of
$delimiter.
2. If your columns are fixed-width, then there is a faster and more
efficient way to extract information from them ( according to the
"Effective Perl Programming" book ):
my @cols = unpack 'A32 A250', $line;
The above example assumes that the key column is always 32 characers
wide and the value column is 250 characters wide. If the key is less
than 32 characters, than you have to add spaces to it's right until
you get a count of 32 characters.
A Complete Example:
use Fcntl ':flock';
my %file = ();
open(FILE, 'foo.txt') or die($!);
flock(FILE, LOCK_SH) or die($!);
while(<FILE>) {
chomp($_);
# The delimiter here is a comma
my @line = split(',', $_);
# Put the key => value pair in the hash
$file{$line[0]} = $line[1];
}
close(FILE);