Generally, I give every record in a database an integer ID number, incrementing by one with every record that I add to the database, never reusing the same ID number, even after a field has been removed. Now, most commercial databases have an "autonumber" feature, or something like that, which automatically assigns a new ID number to each record for you, but when you are working with text files, you don't have anything that nice.
While there is more than one way to do this, here's a suggested way that works consistently for me.
I create an additiona datafile, called ID, or something similar, and put it in the same directory as my data files. This is just a text file with one line in it. To initialize it, I put a number in it, such as 1. If you want to start your ID numbers somewhere else for some reason, you can put any number in there that you like.
I then use a function like the following to get a new I number out of that file for each record.
sub GetID {
my ($file) = @_; # Read in parameters
my ($id, $lock); # Declare additional local variables
# Open the ID file and read in the last number used
open (FILE, "$file");
($id) = <FILE>;
close FILE;
# increment the ID number
$id++;
# Get a lock on the lock file
$lock = $file . ".lock";
open (LOCK, ">$lock");
flock LOCK, 2;
# Write the new ID out to the file
open (FILE ,">$file");
print FILE $id;
close FILE;
# Release lock
flock LOCK, 8;
close LOCK;
# Return the ID number
return $id;
}
Then, from my program, I can call this function to get the next available ID number for my data.
$id = GetID('employee.id')
Several comments on this (in addition to the ones in the code).
($id) = <FILE>reads the contents of the file into the array ($id) which contains only one element. I mention this because it sometimes seems strange to some beginning Perl programmers that $id is a scalar, but ($id) is an array of one element.