Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

RE: push with variable substitution ?

by gnat (Beadle)
on Jun 19, 2000 at 22:33 UTC ( [id://18851]=note: print w/replies, xml ) Need Help??


in reply to push with variable substitution ?

Here's a more detailed response than you've received yet.

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:
$records[5]{NAME}
Definitely learn about references, though. The latest versions of Perl come with MjD's excellent perlreftut manpage, which is a great place to start.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://18851]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (6)
As of 2024-04-18 14:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found