Reputation: 69
I am trying to create a Perl script that allows me access a hash key/value by using a variable.
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.
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};
};
};
Upvotes: 0
Views: 1829
Reputation: 1818
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";
}
Upvotes: 2
Reputation: 69
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"
Upvotes: 0