#!/usr/bin/perl
my $var_a;
$sub_a = "a";
$var_a = "a";
print ${var_."$sub_a"},"\n";
$sub_b = "b";
$var_b = "b";
print ${var_."$sub_b"},"\n";
__DATA__
b
Why is b printed, but not a? This seems like very unexpected behaviour to me.
I’m trying to use a variable with a substituted name. In practice, I cannot just not declare the variable, since the assignment is being done in a forloop and thus has different lexical scope.
Please note that this has NOTHING to do with the fact that you are using variables to contain the name of other variable.
The reason this doesn’t work is because
${"var_a"}construct in reality refers to a package level variable$main::var_a.Since
$var_ais declared as a lexical variable, it’s a DIFFERENT identifyer, and therefore${"var_a"}is undef.You can see that if you change
my $var_atoour $var_aAs others noted, while there is a good explanation for why what you are trying to do doesn’t work, WHAT you are doing is likely the wrong approach. You should almost NEVER use this method unless there’s no better way; without your problem it’s not clear what the better way is but most likely would be a hash like TLP’s answer says.