Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic Perl Variable name

Status
Not open for further replies.

Jboy123

MIS
Jun 8, 2004
24
0
0
CH
Hi All

I'd like to be be able to read in some data from a file, create some variable names based on the data, assign values to these variables and then access the values assigned via the newly created variable name....sorry this is confusing. Something like this:-

File contains

abc 123

If I read in the file I'll want to create a variable name
$abcNum and assign value 123 to it. I can't just put
$abcNum = 123; , in my code because I have no way of knowing what the string on the left column could be before I read in the file.

I tried the following (Normally I would read in each line to get value of var + value but I'll just set them here for now):

$var = "abc";
my $varName = "$var" . "Num";

I then want to assign a value to this variable name. How can I do this?

The end result is that I want to have a variable called:

$abcNum with a value of "123".

I need to be able to access the value 123 via the name $abcNum (but as I say I have no way of knowing that the variable should have this name before opening my data).

Hope this makes some sense. Any help would be appreciated.

Thanks
Jules
 
This is what's known as `soft references', and it's generally a very, very bad idea. You'd be far better off using a hash to store the data, rather than dynamically-created scalar variables. For instance, instead of using $abcNum, you could use $num{abc}, which is an element in the hash %num.

There's are quite a few reasons for avoiding soft references. There's a good article on these available here
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top