How to read associative array from file?

G

Guest

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
 
G

Gunnar Hjalmarsson

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?

What have you tried? Give it a serious try by help of the Perl docs,
and somebody may be willing to help you correct it if needed.
 
M

Mohammd M. Hussain

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);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,138
Messages
2,570,804
Members
47,349
Latest member
jojonoy597

Latest Threads

Top