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
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With