PDA

View Full Version : Dynamic Variable Names


theterabyteboy
Jul 1, 2008, 05:03 PM
I am wondering how to create a variable with a variable name in it.

Ultimately what I want to do is:

my $frequency1 = $frequency;
my $frequency2 = $frequency;
my $frequency3 = $frequency;

but the line my $frequency# = $frequency occurs inside of a loop and I can only
use this instruction once and want to set the value of the appropriate frequency variable.

I have a variable named $attempts and attempts holds the value 1, then 2, and then 3 on the third iteration of the loop

I am trying to use some sort of command like:

my $frequency{$attempts} = $frequency;

but this is not working, can someone please help? Thank you very much.

derobert
Jul 5, 2008, 12:01 PM
You can refer to non-my variables by name, the syntax looks like this:

$frequency2 = 10;
my $var_name = "frequency2";
print $$var_name, "\n";

but you probably don't want to. If you have a list of frequencies, you probably want to use an array. E.g.

my @frequencies = (10, 20, 30);

for (my $i = 0; $i < 2; ++$i) {
print $frequencies[$i], "\n";
}

Or, you could use foreach, map, etc. to iterate over the array.