How to define variable names dynamically in Perl 6?

倖福魔咒の 提交于 2019-12-05 11:58:14

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

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