【问题标题】:In Perl, how can I use the contents of a variable as the name of a hash? [duplicate]在 Perl 中,如何使用变量的内容作为哈希的名称? [复制]
【发布时间】:2026-01-07 13:55:01
【问题描述】:

以下代码仅在没有严格限制的情况下有效。 任何人都可以提出更好的方法吗?

%hash5=('key5', 5);
my $hash_name = 'hash5';
print $$hash_name{'key5'}, "\n";

我的目标是:我不知道哈希名称。我只知道,它是存储在 变量 $hash_name。人们一直在建议这样的事情:

 my $hashref = \%hashABC;

这需要我知道哈希名称是 '%hashABC'。 使用上面的这个例子,我想做一些事情:

 my $hash_name = 'hashABC'; 
 my $hashref = \%$hash_name; # not possible, hope u get the aim

现在我不再需要知道哈希的名称了。 这就是我想要的。

谢谢很多人! (perl 5)

【问题讨论】:

  • 但是,当您执行my $hash_name = 'hash5'; 时,您需要知道哈希名称。设置引用后,我也不再需要实际的哈希名称。
  • 抱歉,这种方法既不比其他方法更易读也更直观,并且很可能引入难以发现的错误。请改用散列散列或散列数组。例如,my %people = ( bob => { age => 55, phone => '123-4567' }, fred => { age => 42, phone '345-6789' } ); 要打印所有电话号码,请执行 foreach my $person (keys %people) { print $people{$person}{phone}, "\n"; }
  • 您还可以使用对象来封装您的数据,允许您执行以下操作:foreach my $person (@people) { print $person->phone_number, "\n"; } 请参阅perldoc perlootut

标签: perl hash strict


【解决方案1】:

不要按名称引用哈希,而是使用引用。

# Here is our hash
my %hash = (key => 5);
# we make a reference to the hash
# this is like remembering the name of the variable, but safe
my $hashref = \%hash;

# here are two ways to access values in the referenced hash
say $$hashref{key};
say $hashref->{key}; # prefer this

或者,保留一个哈希值,以便您可以按名称查找项目:

# here is our hash again
my %hash = (key => 5);
# and here is a hash that maps names to hash references
my %hash_by_name;
# we remember the %hash as "hash5"
$hash_by_name{hash5} = \%hash;

# now we can access an element in that hash
say $hash_by_name{hash5}{key};

# we can also have a variable with the name:
my $name = "hash5";
say $hash_by_name{$name}{key};

详细了解perlreftut 中的参考资料。

【讨论】:

  • 嗨,您并没有真正通过变量访问哈希。在这两种情况下,您都需要知道您的哈希称为“哈希”。因此,不幸的是,它没有回答我的问题。
  • @user152037 我添加了一些 cmets 来阐明我在做什么。如果这不能回答您的问题,恐怕我不太明白 - 请编辑您的问题以使其更清楚。
  • 已编辑!请检查以上
【解决方案2】:

在这种情况下,暂时禁用strict 看起来是最好的解决方案,你可以这样做

#!/usr/bin/perl

use strict;
use warnings;

our %hash5=('key5', 5);
my $hash_name = 'hash5';

my $hash_ref;

{
    no strict "refs";
    $hash_ref = \%$hash_name;
}

print $hash_ref->{key5}, "\n";

注意:为此,%hash5 必须是全局变量。

【讨论】:

  • 对不起。我无法在 perldoc perlref 得到答案。它只是重复此处和相关问题中提出的解决方案。但不完全是我问题的解决方案。或者是我,谁没有得到它? :-)
  • @user152037 看起来暂时禁用strict refs 是你能得到的最好的。
【解决方案3】:

我不知道%hash_name 中的数据来自哪里。您是否阅读并存储在%hash_name 中?如果是这样,也许更简单的解决方案是修改您的程序以读入散列哈希(正如许多人所建议的那样),而不是读入全局变量:

my %data = (
    hash_name => get_data(),
);
# and then ...
my $name = get_name(); # e.g., 'hash_name'
my $data = $data{ $name } or do {
    # error handling
    ...
};

请记住,use strict 施加的限制根本不适用于哈希 :-) 的键

【讨论】:

    最近更新 更多