views:

121

answers:

2

Possible Duplicate:
How can I use a variable as a variable name in Perl?

Is this doable? I need to change a string into variable.

Example:

If I have a variable like this:

$this_is_test = "what ever";
$default = "this";
$default = $default . "_is_test";

I want $default to take the value of $this_is_test.

+2  A: 

As rafl said, this can be achieved through symbolic references, but they are quite dangerous (they are a code injection vector) and don't work with lexical variables (and should be using lexical variables instead of package variables). Whenever you think you want a symbolic reference, you almost certainly want a hash instead. Instead of saying:

#$this_is_test is really $main::this_is_test and is accessible from anywhere
#including other packages if they use the $main::this_is_test form 
our $this_is_test = "what ever";
my $default       = "this";
$default          = ${ $default . "_is_test" };

You can say:

my %user_vars = ( this_is_test => "what ever" );
my $default   = "this";
$default      = $user_vars{ $default . "_is_test" };

This limits the scope of %user_vars to the block in which it was created and the segregation of the keys from the real variables limits that danger of injection attacks.

Chas. Owens
@Chas. It looks like part of the last sentence got cut-off.
Sinan Ünür
@Sinan Ünür Thanks, I must have gotten distracted.
Chas. Owens
+2  A: 

Along the lines of my other answer, whenever you find yourself adding string suffixes to a variable name, use a hash instead:

my %this = (
    is_test => "whatever",
    is_real => "whereever",
);

my $default = $this{is_test};

print "$default\n";

Do NOT use symbolic references for this purpose because they are unnecessary and likely very harmful in the context of your question. For more information, see Why it's stupid to 'use a variable as a variable name'?, part 2 and part 3 by mjd.

Sinan Ünür
Thanks, I used the hash, yet it is not wrong to learn the other ways..By the way it seems that u added an extra _ in the hash key _is_test.
zeina