Main Content

Perl - the duplicate key problem explained, and solutions offered

Archive - Originally posted on "The Horse's Mouth" - 2010-06-28 15:10:17 - Graham Ellis

Do you want to hold data in a hash in Perl - but you can't do so directly because you have more than one piece of data that should have the same key?

The problem ...

while (<DIAL>) {
  ($dial,$place) = split
  $codes{$place} = $dial;
  }


And each line that contains a repeated place name OVERWRITES the previous record for that names place. The problem is shown - this code above in a worked example - [here]. When we run it:

-bash-3.2$ perl stdhash
4898 lines read
4742 entries in hash
Florida: 001954
-bash-3.2$


we only get one Florida entry, and we notice that rather more lines were read than records created.

The solution ...

This is Perl and there are more than one way of doing anything, so take your pick!

1. Store all the possible codes in a string or list within the hash. [source example]

or 2. Make up a new key if the one you want has already been used. [source example]. But note that will only report on the original key, you you'll need to add something to find the other generated keys too - see [source example].

The data file used in these examples may be found [here].