Forum Moderators: coopster & phranque

Message Too Old, No Replies

How To Dynamically Create a Dynamic Array Variable

         

incrediBILL

12:56 am on May 30, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have a situation where I have a random array of variable names that I need to convert into an actual variable name because the code already references the original variable name.

I have other ways I could do this, a little more complicated code perhaps, but I was hoping there was an easy way to do it that avoids nasty code.

Here's the situation, the data is in a file like this:

$somevar = 10;
$anothervar = 20;
$thisarray{"myvar"} = 30;
$thisarray{"myvar2"} = 40;

These are read into an array and I can convert them into their actual variable names on the fly using code like this:
${"somevar"}="test";
Then you can print $somevar and it displays "test";
Easy enough to just wrap all variable names in ${} right?
Wrong.

${"thisarray{\"myvar\"}"} = 30;
That doesn't work, $thisarray{"myvar"} is blank.

Any ideas on syntax that would work?
I've tried several variations for fun, nothing worked.

This particular problem is hard to find a solution to because all of the query results about making dynamic arrays usually resolves to hash array stuff, never this.

Anyone got any ideas?

phranque

9:54 am on Jun 2, 2015 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



perhaps a few concepts will help:

$thisarray{"myvar"} = 30;

this has nothing to do with an array.
this is a scalar value assignment to the 'myvar' key of the %thisarray hash.

${"somevar"}="test";

putting braces around the variable name is useful for disambiguating a variable name.
for example it would be useful in the following assignment:
$text= '${somevariablename}followedbytext';


${"thisarray{\"myvar\"}"} = 30;

perhaps this is what you need:
${"thishash"}{"mykey"} = 30;

incrediBILL

4:10 am on Jun 4, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yup, your last line is probably just exactly what I need.

The problem with trying to find about anything about making actual dynamic variables is you end up on pages about hash arrays because people don't know what the hell they're talking about and the SE is totally clogged up with the wrong thing.

incrediBILL

11:09 pm on Jun 5, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



FYI, thanks Phranque, worked like a charm!