Any time you find yourself saying "I have the name of a variable in a string, and I want the value in that variable", stop.
You're programming like a Perl 4 programmer. You are using the symbol table to build your data structures. Back in those days you couldn't have an array of hashes. But you could have an array containing the names of hashes. Here you're building a data structure that's a hash whose values are arrays. You're using the symbol table as the top-level hash.
The solution is to use Perl 5 programming techniques, namely references. You can actually have a hash of arrays, so when you look up a string like "alpha" or "num" you get back a reference to an array.
Your code would then look like:
foreach $var (@vars) {
push @{ $myhash{$var} }, $var;
}
It looks like you're reading a file a record at a time.
Each record contains a bunch of fields. You want an
array for each field, so that $name[0] is the name of
the 0th person, $age[0] is the age of the 0th person,
etc.Each record you read, you split into $name, $age, and so on. Then you need some magic to push $name onto @name, $age onto @age, etc.
There is two solutions to this problem. The first is to split into a hash: $person{name}, $person{age}, etc. Then you can do:
foreach $field (keys %person) {
push @{ $myhash{$field} }, $person{$field};
}
A better approach, depending on what you're going to do
with the data, might be to have an array of records. Then
for each record, you simply do:
my %record;
# populate $record{NAME}, $record{AGE}, etc
push @records, \%record;
Now if you want to talk about the 5th person's name,
say:
Definitely learn about references, though. The latest versions of Perl come with MjD's excellent perlreftut manpage, which is a great place to start.$records[5]{NAME}
In reply to RE: push with variable substitution ?
by gnat
in thread push with variable substitution ?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |