Perl, accessing a variable by name in another scalar

I'm sure this works with perl, but I don't know how to encode it. I can imagine this with eval, but that's not what I'm 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.

thank

+3
source share
4 answers

Perl has two separate, but largely compatible variable systems.

Package variables that are either fully qualified names $Some::Package::variableor lexical names declared with our. The package variables located in the symbol table are global for the entire program, can be the object of symbolic dereferencing, and can be provided by the dynamic scope with local.

, my, . ( , ). , . $$varname , .

:

  • , , our, :

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

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

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

, , . , , , . , .

+1

, , , ${$varname} ( $$varname ). , . use strict.

no strict 'refs', , , , .

. , , , .

+8

$$varname = 1 , , , use strict; , .

+3

Perl :

http://learn.perl.org/faq/perlfaq7.html#How-can-I-use-a-variable-as-a-variable-name-

It contains detailed information about warnings, examples, and alternatives.

0
source

All Articles