![]() |
|
|
| Subject:
simple perl question - read file into hash array
Category: Computers > Programming Asked by: carl655321-ga List Price: $5.00 |
Posted:
21 Aug 2002 09:02 PDT
Expires: 20 Sep 2002 09:02 PDT Question ID: 56968 |
I need to read data from a file into a perl hash (associative array)
table. The data in the file consists of just a list of names (first
and last names of each person on the same line, and each person on a
different line.) I need the names to all = 0, too. So, for example,
once the file is read into the hash table, I should be able to
reference it's value with:
print $hash_table{"name_first name_last"};
And, this should print out 0 (and every record should be 0), because
that's what it was assigned to when the hash was created. The name
file looks like this:
first_name1 last_name1
first_name2 last_name2
first_name3 last_name3
etc.
Please help! |
|
| Subject:
Re: simple perl question - read file into hash array
Answered By: iaint-ga on 21 Aug 2002 10:00 PDT Rated: ![]() |
Hi carl655321
The following little snippet of code should do exactly what you want:
open(IN, "<name_file")
or die "Couldn't open file for processing: $!";
while (<IN>) {
chomp;
$hash_table{$_} = 0;
}
close IN;
Once you've read in your values, the following single line of code
will print them all out for you:
print "$_ = $hash_table{$_}\n" foreach keys %hash_table;
I hope that the above meets your needs. If I've misunderstood your
question, or if you'd like some explanation of how the program works,
please feel free to request a clarification and I'll do my best to get
what you require.
Regards
iaint-ga | |
| |
| |
carl655321-ga
rated this answer:
I am very satisfied with this answer; it was _very_ quick, and accurate. Thank you! |
|
| Subject:
Re: simple perl question - read file into hash array
From: pne-ga on 21 Aug 2002 11:11 PDT |
What version of perl are you using? (Running "perl -v" will tell you.)
The "missing $ on loop variable" sounds as if you have an older
version that doesn't like "STATEMENT foreach EXPR".
Try rewriting the code
print "$_ = $hash_table{$_}\n" foreach keys %hash_table;
as
foreach (keys %hash_table) {
print "$_ = $hash_table{$_}\n";
}
and see whether that makes a difference. If that solves your problem,
then your perl is probably too old. Perhaps you can upgrade? I'd
recommend version 5.6.1, though you can also try 5.8.0 if you don't
mind using a .0 version.
Also, the code
print table${"record name"};
is incorrect; you probably mean
print $hash_table{"record name"};
instead (dollar sign before the variable, not after it -- this is Perl
not Visual Basic :) |
If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you. |
| Search Google Answers for |
| Google Home - Answers FAQ - Terms of Service - Privacy Policy |