问题
I have a name which I'd like to give to a variable, in another string variable:
my $name = '$a';
or simply my $name = 'a';
How to make the variable and to use it? I mean something like this (but it doesn't work):
my $name = '$a';
my {$name} = 1; # Doesn't work
say $a; # should be 1
A more general case. I have a list of variable names, say my @names = '$aa' ... '$cc';
How to declare and use the variable, whose name will be e.g. @names[2]
?
回答1:
According to documentation the lexical pad (symbol table) is immutable after compile time. Also (according to the same docs) it means EVAL
cannot be used to introduce lexical symbols into the surrounding scope.
I suggest you use package variables, instead of lexical variable as suggested in the comments.
However, a workaround is possible: You can create your own lexical pad at run time (for the module requiring) using for example require MODULE
:
my $name = '$a';
spurt 'MySymbols.pm6', "unit module MySymbols; use v6; my $name = 1; say \"\\$name = $name\"";
use lib '.';
require MySymbols;
Output:
$a = 1
回答2:
Lexical scopes are immutable, but the way you would do it is ::($name)
or MY::($name)
.
my $a; # required or it will generate an error
my $name = '$a';
::($name) = 1;
say $a; # 1
MY::($name) = 2;
say $a; # 2
sub foo ($name,$value) { CALLER::MY::($name) = $value }
foo($name,3);
say $a; # 3
来源:https://stackoverflow.com/questions/47332941/how-to-define-variable-names-dynamically-in-perl-6