Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can I use a string as a variable name? [duplicate]

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.

like image 895
Luci Avatar asked Oct 06 '10 10:10

Luci


2 Answers

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.

like image 86
Chas. Owens Avatar answered Oct 20 '22 00:10

Chas. Owens


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.

like image 22
Sinan Ünür Avatar answered Oct 20 '22 00:10

Sinan Ünür