0

I'm trying to work with hash tables in perl. I'm facing a problem when i'm using an array index as a key in the hash table.

my @array;
my %Mappings;
$Mappings{$array[0]} = 'First';
$Mappings{$array[1]} = 'Second';
print "$Mappings{$array[0]} \n $Mappings{$array[1]} \n";

The output of this code is always Second. I'm unable to access the value First with this code.

Should I be considering any other steps to access the value First ?

2 Answers 2

3

Given both $array[0] and $array[1] are undefined, they'll map to an empty string for hash access. So yeah it is expected that they'll refer to the same element.

Can you explain what you're trying to achieve?

Sign up to request clarification or add additional context in comments.

1 Comment

I have an array that contains a set of elements. I'm trying to make these elements as Keys for the hash table. I was thinking if it would be possible to access the values of the hash table this way.
0

If your elements have the same value, e.g., undef, 1, 2, 'a' ... then you will get the same hash. To avoid this you can use the address of the array element:

use warnings;
use strict;
my @array = ('1', '1');
my %Mappings;
$Mappings{\$array[0]} = 'First';
$Mappings{\$array[1]} = 'Second';
print "$Mappings{\$array[0]} \n $Mappings{\$array[1]} \n";

2 Comments

Your answer does the job ! To clarify your explanation, you mean, if my array elements have the same value, they end up getting the same hash ?
that's right, if your keys are identical then you will fetch the same value.

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.