在Perl中,如何使用变量的内容作为散列的名称?
下面的代码只适用于没有严格限制的情况。 有人能提出更好的方法吗在Perl中,如何使用变量的内容作为散列的名称?,perl,hash,strict,Perl,Hash,Strict,下面的代码只适用于没有严格限制的情况。 有人能提出更好的方法吗 %hash5=('key5', 5); my $hash_name = 'hash5'; print $$hash_name{'key5'}, "\n"; 我的目标是:我不知道散列名。我只知道,它在商店里 变量$hash_name。人们一直在建议: my $hashref = \%hashABC; 这要求我知道哈希名称是“%hashABC”。 使用上面的例子,我想做如下事情: my $hash_name = 'hashABC
%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)使用引用,而不是按名称引用哈希
# 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};
了解有关中引用的更多信息。在这种情况下,暂时禁用
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
必须是一个全局变量。我不知道%hash\u name
中的数据来自何处。您是否阅读并将其存储在%hash\u 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
...
};
请记住,
使用strict
施加的限制根本不适用于散列的键:-)
嗨,您并不是真正通过变量访问散列。在这两种情况下,您都需要知道您的哈希被称为“哈希”。不幸的是,它没有回答我的问题。@user152037我添加了一些注释来澄清我在做什么。如果这还不能回答你的问题,恐怕我不太明白-请编辑你的问题,让它更清楚。编辑!检查一下上面的桌子。我在perldoc perlref得不到答案。它只是重复了这里和相关问题中提出的解决方案。但这并不是我问题的答案。还是我,谁没有得到它?:-)@user152037看起来暂时禁用strict refs
是最好的。但是,在执行my$hash_name='hash5'时,您需要知道哈希名称代码>。一旦我设置了一个引用,我也不再需要实际的哈希名称。请参见。请参见,也很抱歉,但这种方法既不比其他方法更易读,也不比其他方法更直观,而且很可能会引入难以发现的错误。改为使用散列或散列数组。例如,my%people=(bob=>{age=>55,phone=>'123-4567'},fred=>{age=>42,phone'345-6789'})
要打印所有电话号码,请执行以下操作:foreach my$person(key%people){print$people{$person}{phone},“\n”}
您还可以使用对象封装数据,允许您执行以下操作:foreach my$person(@people){print$person->phone\u number,“\n”}
请参见。