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

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

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

Example:

If I have a variable like this:

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

I want $default to be set to $this_is_test .

+4
source share
2 answers

In strings, my other answer is , whenever you add 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 links for this purpose, because they are unnecessary and probably very harmful in the context of your question. For more information, see Why is it stupid to use a variable as a variable name? , part 2 and part 3 of the MJD .

+11
source

As rafl said, this can be achieved using symbolic links, but they are quite dangerous (they are a vector of code injection) and do not work with lexical variables (and should use lexical variables instead of package variables). Whenever you think you want a symbolic link, 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 block in which it was created, and the separation of keys from real variables limits the risk of injection attacks.

+4
source

All Articles