Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!mips!cs.uoregon.edu!ogicse!intelhf!ichips!iwarp.intel.com!gargoyle!chinet!les From: les@chinet.chi.il.us (Leslie Mikesell) Newsgroups: comp.lang.perl Subject: Re: using contents of a scalar variable as a variable name Message-ID: <1991Apr12.155453.14627@chinet.chi.il.us> Date: 12 Apr 91 15:54:53 GMT References: Organization: Chinet - Chicago Public Access UNIX Lines: 40 In article knodel@spot.Colorado.EDU writes: >In a perl application I am writing, I would find it extremely useful >to reference variables whose names are stored in an array. The only >way which consistently worked was to use an eval statement. I've found that most places where you might want to do this are easier to handle with associative arrays. >For example, >if I have an array: >@names=("john","joe","paul"); >and I want to assign values to the variables whose names appear >in the array (in this case, $john, $joe, and $paul). I found that >I could reference them via an eval statement, like: >print eval("\$$names[0]"); For associative arrays the name itself is the key that is used to reference the associated value and expansion of a different variable into the key is just $array{$variable}, which can be used for reference or assignment without any special tricks. >but assigning to them via this method was a little gross: >eval("\$$names[0] = \"something\"); >Is there a better way to reference these variables? With associative arrays, you would have a %names array and you might not even need the @names array containing the keys since you can reference the associative elements directly: $names{"john"} = 10; or $name = "john"; $names{$name} = 10; and you can obtain the current list of names with the keys() operator: @names = keys(%names); if you happen to need it. Since you can iterate over all the defined elements of an associative array, you probably only need the list of keys if you want to sort them: @names = sort(keys(%names)); This is the kind of stuff that makes using perl fun. No need to pre-allocate anything - just read your input into variables, then assign or total to the values associated with the constructed keys. Les Mikesell les@chinet.chi.il.us