467,915 Members | 1,537 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,915 developers. It's quick & easy.

How to read associative array from file?

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

Jul 19 '05 #1
  • viewed: 10653
Share:
2 Replies
nospam wrote:
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.

--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
Jul 19 '05 #2
nospam <no@spam.com> wrote in message news:<pa****************************@spam.com>...
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);
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by mark4asp | last post: by
4 posts views Thread by Robert | last post: by
5 posts views Thread by soup_or_power | last post: by
7 posts views Thread by Robert Mark Bram | last post: by
1 post views Thread by swayze | last post: by
code green
8 posts views Thread by code green | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.