[英]Referencing hash keys with a variable in perl
I am trying to create a Perl script that allows me access a hash key/value by using a variable. 我试图创建一个Perl脚本,该脚本允许我使用变量访问哈希键/值。
The code below is a very high level example of script does. 下面的代码是脚本功能的一个非常高级的示例。 Is there any way to reference the key of the hash with a variable?
有什么方法可以用变量引用哈希键吗? It looks like the $hash_exmp{$temp_var} is not being accepted.
似乎$ hash_exmp {$ temp_var}没有被接受。
my %hash_exmp = (
$key_1 => "file1",
$key_2 => "file2",
$key_3 => "file3",
);
for($i = 1; $i <= 3; $i++){
for($j = 1; $j <= 3; $j++){
print $j;
$temp_var = "key_${i}";
print $hash_exmp{$temp_var};
};
};
If I understand correctly what you are trying to do, you want something like this: 如果我正确理解您要做什么,那么您将需要以下内容:
my %hash_exmp = (
'key_1' => "file1",
'key_2' => "file2",
'key_3' => "file3",
);
for(my $i = 1; $i <= 3; $i++){
print $hash_exmp{'key_'.$i} . "\n";
}
The issue was making my keys as variables when I changed them to string names it works. 问题是,当我将键更改为字符串名称时,将键作为变量使用是可行的。 In other words I changed from $key1 => "file1" to key1 => "file1"
换句话说,我从$ key1 =>“ file1”更改为key1 =>“ file1”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.