在另一个包中设置变量

时间:2010-11-25 16:14:22

标签: perl

我想在另一个包中设置一个带有所选名称的变量。我怎么能这么容易地做到这一点?

类似的东西:

$variable_name = 'x';
$package::$variable_name = '0';
# now $package::x should be == '0'

3 个答案:

答案 0 :(得分:2)

你可以这样做,但你必须禁用这样的限制:

    package Test;

    package main;

    use strict;

    my $var_name = 'test';
    my $package = 'Test';

    no strict 'refs';
    ${"${package}::$var_name"} = 1;

print $Test::test;

所以我不推荐。最好使用哈希。

答案 1 :(得分:2)

use 5.010;
use strict;
use warnings;

{
    no warnings 'once';
    $A::B::C::D = 5; # a test subject
}

my $pkg = 'A::B::C';
my $var = 'D';

# tearing down the walls (no warranty for you):
    say eval '$'.$pkg."::$var"; # 5

# tearing down the walls but at least feeling bad about it:
    say ${eval '\$'.$pkg."::$var" or die $@}; # 5

# entering your house with a key (but still carrying a bomb):
    say ${eval "package $pkg; *$var" or die $@}; # 5

# using `Symbol`:    
    use Symbol 'qualify_to_ref'; 
    say $${ qualify_to_ref $pkg.'::'.$var }; # 5

# letting us know you plan mild shenanigans
# of all of the methods here, this one is best
{
    no strict 'refs';
    say ${$pkg.'::'.$var}; # 5
}

如果以下内容对您有意义,请致电:

# with a recursive function:
    sub lookup {
        @_ == 2 or unshift @_, \%::;
        my ($head, $tail) = $_[1] =~ /^([^:]+:*)(.*)$/;
        length $tail
            ? lookup($_[0]{$head}, $tail)
            : $_[0]{$head}
    }
    say ${ lookup $pkg.'::'.$var }; # 5

# as a reduction of the symbol table:
    use List::Util 'reduce';
    our ($a, $b);

    say ${+ reduce {$$a{$b}} \%::, split /(?<=::)/ => $pkg.'::'.$var }; # 5

当然,您可以分配到这些方法中的任何一种而不是say

答案 2 :(得分:1)

鉴于$variable_name已经过验证,您可以执行以下操作:

eval "\$package::$variable_name = '0'";