0

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};
    };
};
4
  • 4
    You've got a bunch of issues with this code (which would be highlighted if you use strict; use warnings;) which might explain the problem you are having. I don't know if they are the cause of your real problem or if your attempt to create a minimal reproducible example is just showing a different set of problems. Commented Oct 1, 2018 at 16:36
  • 1
    Did you mean $key_1 => "file1" or rather key_1 => "file1" ? Commented Oct 1, 2018 at 16:49
  • If you are trying to use a variable to store a variable name, that is a bad idea. Commented Oct 1, 2018 at 16:50
  • The issue was making my keys as variables when I changed them to string names it works, thanks! Commented Oct 1, 2018 at 17:09

2 Answers 2

2

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";
}
Sign up to request clarification or add additional context in comments.

1 Comment

And for(my $i = 1; $i <= 3; $i++) can be simplified to for my $i (1..3)
0

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"

1 Comment

You can use a variable for a key in a hash, my %h = ($key_name => 1) but that variable must be defined beforehand (my $key_name = 'id';) and then it will be evaluated and your "actual" key is that (the string 'id' in this example). Then you can work with it using a variable as well, $h{$var}, as long as that $var evaluates to the string 'id', for $h{id} (may drop quotes for a hash key when it's a clean literal). If you don't know whether a key exists for a string that a variable evaluates to then you can check, if (exists $h{$var}) ... .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.