To implement rovf's suggestion:
use Data::Dumper;
use strict;
use warnings;
my %hash;
assignWithDupes([
"one" => "1",
"two" => "2",
"one" => "3",
"three" => "4",
"two" => "5",
"one" => "6",
],
\%hash);
print Dumper(\%hash);
sub assignWithDupes {
my ($arr, $hash) = @_;
my ($i, $j, $key, $val);
for ($i = 0; $i < $#$arr; $i += 2) {
$key = $arr->[$i];
$val = $arr->[$i+1];
if (!defined $hash->{$key}) {
$hash->{$key} = $val;
next;
}
for ($j = 2; defined $hash->{"${key}_$j"}; $j++) {}
$hash->{"${key}_$j"} = $val;
}
}
Output (modified to put it in order):
$VAR1 = {
'one' => '1',
'one_2' => '3',
'one_3' => '6'
'two' => '2',
'two_2' => '5',
'three' => '4',
};
As you can see, successive instances of the same key are assigned to _2, _3, etc. |