Perl,按其他标量中的名称访问变量 [英] Perl, access variable by name in an other scalar

查看:43
本文介绍了Perl,按其他标量中的名称访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很确定这适用于 perl,但我不知道如何编码.我可以用 eval 来想象,但这不是我要找的.

I am pretty sure this works with perl but I dont know how to code it. I can imagine it with eval, but that is not I am looking for.

my $foo = 0;
my $varname = "foo";


$($varname) = 1;  # how to do this? 
# I want to access a scalar that name is in a other scalar
# so $foo should be 1 now.

谢谢

推荐答案

Perl 有两个独立但在很大程度上兼容的变量系统.

Perl has two separate but largely compatible variable systems.

包变量,可以是完全限定名称$Some::Package::variable 或用our 声明的词法名称.包变量存在于符号表中,对整个程序是全局的,可以是符号解引用的目标,并且可以通过 local 赋予动态范围.

Package variables, which are either fully qualified names $Some::Package::variable or lexical names declared with our. Package variables live in the symbol table, are global to the whole program, can be the target of a symbolic dereference, and can be given a dynamic scope with local.

my 声明的词法变量构成了另一个变量系统.这些变量不存在于包或符号表中(而是存在于附加到作用域的词法垫中).这些变量不是全局的,不能被符号引用,也不能有动态范围.这就是为什么你不能使用 $$varname 并期望它找到一个词法变量.

Lexical variables, declared with my, comprise the other variable system. These variables do not live in a package or symbol table (instead they live in a lexical pad which is attached to a scope). These variables are not global, can not be symbolically referenced, and can not have dynamic scope. This is why you can not use $$varname and expect it to find a lexical variable.

您有几种方法可以解决这个问题:

You have a few ways to deal with this issue:

  • 使用包变量,无论是完全限定名,还是用our声明,严格禁止,并使用符号引用:

  • use package variables, either fully qualified names, or declared with our, keep strict off, and use symbolic references:

our $x = 1;
our $y = 'x';
say $x;  # 1
$$y = 5; # this line is an error if `use strict` is loaded
say $x;  # 5

  • 使用包变量并遍历符号表:

  • use package variables and walk the symbol table:

    $main::x = 1;
    my $y = 'x';
    
    ${$main::{$y}} = 5;  # ok with `use strict`
    say $main::x;  # 5
    

  • 最佳实践方式是使用散列(这是上面两个例子在幕后所做的,因为符号表本身就是一个散列)

  • the best practices way is to use a hash (which is what the above two examples are doing behind the scenes, since the symbol table itself is a hash)

    my %data = (x => 1);
    my $y = 'x';
    $data{$y} = 5;
    say $data{x};  # 5
    

  • 符号引用的危险在于,将您的程序变成意大利面条式代码或覆盖您不打算覆盖的变量通常太容易了.通过使用显式散列,您可以将您正在做的事情的魔力限制在明确定义和有限的范围内.散列本身可以是词法的,允许对变量进行适当的自动垃圾回收.

    The danger with symbolic references is that it is often far too easy to turn your program into spaghetti code, or to overwrite variables that you did not intend to. By using an explicit hash, you limit the magic of what you are doing to a well defined and limited scope. The hash itself can be lexical, allowing proper automatic garbage collection of your variables.

    这篇关于Perl,按其他标量中的名称访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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