0
my $myvar = "foo";
my $x = "my";
my $y = "var";

print ${$x$y};  # output is foo?

How can I use a variable to make up a variable name?

CJ7
  • 22,579
  • 65
  • 193
  • 321
  • 2
    https://metacpan.org/pod/perlfaq7#How-can-I-use-a-variable-as-a-variable-name – Andy Ray Aug 10 '16 at 04:56
  • 5
    Note that using `use strict;` prevents you from doing it. Are you sure you want it? Using the technique usually means things are not properly organized (maybe you should be using a hash). – Jonathan Leffler Aug 10 '16 at 05:02
  • https://eval.in/620376 – mpapec Aug 10 '16 at 09:24
  • The bottom line is *don't do it*. It looks like you want a hash, say `%values`. Then you can write `$values{myvar} = 'foo'` and `print $values{$x.$y}` and get the correct result. – Borodin Aug 10 '16 at 09:28
  • 3
    [Why it's stupid to use a variable as a variable name](http://perl.plover.com/varvarname.html) – Sobrique Aug 10 '16 at 09:52
  • @JonathanLeffler I don't think that's the best dupe target, since the clear solution to that question is to use an array. I think [this question](http://stackoverflow.com/q/26473593/176646) would be better (and I just cleaned it up to make it a suitable canonical). Edit: On second thought, the other question should also use an array, so maybe neither is a great dupe target. Oh well. – ThisSuitIsBlackNot Aug 10 '16 at 14:52
  • @ThisSuitIsBlackNot: Both [How can I use a variable as a variable name in Perl?](http://stackoverflow.com/questions/1549685/) and [How can I combine two strings and treat the result as the name of a variable?](http://stackoverflow.com/questions/26473593/) cover the territory — and the first listed was answered 5 years earlier. Either could be used as a duplicate — I don't think the difference is big enough to warrant changing, but if some other Perl Mjölnir-wielder disagrees and switches, I won't fight over it. – Jonathan Leffler Aug 10 '16 at 15:01

0 Answers0