How to define variable names dynamically in Perl 6?

拈花ヽ惹草 提交于 2019-12-07 10:34:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!