【问题标题】:Can't use string ("VIEW_hash") as a HASH ref while "strict refs" in use at test.pl line 10在 test.pl 第 10 行使用“严格引用”时,不能使用字符串(“VIEW_hash”)作为 HASH 引用
【发布时间】:2011-09-19 09:47:50
【问题描述】:

嗨,我真的需要一个变量作为哈希名称。但我收到了这个错误。有人可以帮忙吗?

#!/usr/bin/perl -w

use strict;

my %VIEW_hash = ( 'a' => 'A', 'b' => 'B', 'c' => 'C');
my $X = "VIEW";
my $name = "$X"."_hash";

foreach my $in (keys %$name){
    print "$in -- $$name{$in}\n";
}

【问题讨论】:

    标签: perl hash


    【解决方案1】:

    我怀疑你真的需要这样做。很可能,您只是想打破规则,因为您不知道更好的方法。

    考虑使用散列来存储文本链接到您的实际数组:

    my %VIEW_hash = ( 'a' => 'A', 'b' => 'B', 'c' => 'C');
    my $X = "VIEW";
    my $name = "$X"."_hash";
    
    # Our new code
    my %meta = ( "VIEW_hash" => \%VIEW_hash );
    my $href = $meta{$name};
    
    say @$href{"a".."c"};
    say $href->{a}
    

    【讨论】:

    • 我同意,不要违反规则。仅在确实需要时才这样做,并且只有在没有其他方法可以完成工作时才这样做。
    【解决方案2】:

    我改变了一些东西,但这可能符合你的需要。

    首先你必须使用no strict 'refs' pragma,才能使用符号引用。然后你必须从词法变量切换到包变量(用our定义)。

    我选择将无狭窄区域的扩展限制为用花括号括起来的块:它可能会在将来为您省去一些麻烦。

    #!/usr/bin/perl -w
    
    use strict;
    {
        no strict 'refs';
        our %VIEW_hash = ( 'a' => 'A', 'b' => 'B', 'c' => 'C');
        my $X    = 'VIEW';
        my $name = "$X".'_hash';
    
        foreach ( keys %$name ) {
            printf "%s -- %s\n", $_, $$name{ $_ };
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-25
      • 2015-06-18
      • 2022-01-15
      • 2018-04-08
      • 2023-03-31
      • 2020-05-22
      • 1970-01-01
      • 2011-12-05
      • 2020-02-21
      相关资源
      最近更新 更多