Reputation: 167
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 ?
Upvotes: 0
Views: 348
Reputation: 97918
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";
Upvotes: 0
Reputation: 30225
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?
Upvotes: 3