如何在 Perl 6 中动态定义变量名? [英] How to define variable names dynamically in Perl 6?

查看:74
本文介绍了如何在 Perl 6 中动态定义变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给一个变量取一个名字,在另一个字符串变量中:my $name = '$a'; 或者干脆 my $name = 'a'; 如何制作变量并使用它?我的意思是这样的(但它不起作用):

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

更一般的情况.我有一个变量名称列表,比如 my @names = '$aa' ... '$cc'; 如何声明和使用变量,其名称将是例如@names[2]?

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]?

推荐答案

根据文档词法垫(符号表)在编译后是不可变的.此外(根据相同的文档)这意味着 EVAL 不能用于将词法符号引入周围的范围.

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.

但是,一个解决方法是可能的:您可以在运行时(对于需要的模块)使用例如 require MODULE 来创建自己的词汇垫:

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;

输出:

$a = 1

这篇关于如何在 Perl 6 中动态定义变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆