Wednesday, April 13, 2011

Generating random unique codes in PERL

This post will teach you how to generate random unique codes in PERL. Just follow the simple steps below. Enjoy!!

1. Create an array of character set combination. Below was set to 29 alphanumeric characters excluding other characters with similarities.

my @arrCharset = split //, "abcdefhjkmnpqrstuvwxyz2345678"; # 29 alphanumeric characters

2. Set the number of random codes you want to generate and set it into the loop.

$intCodes = 540000; # this will generate 540,000 random codes.
for ($i=1; $i<=$intCodes; $i++)
{
  ##.......... see step #3 ..........
  ##.......... see step #5 ..........
}

3. Inside the loop in step #2, set the number of characters you wanted on each code and create a loop to generate random code.

$intCharCnt = 6; # this will generate 6 characters per code.
for ($l=1; $l<=$intCharCnt; $l++)
{
  ##.......... see step #4 ..........
}

4. Inside the loop in step #3, pick a random character in the character set in step #1 and generate the code. 

$intRand = int(rand(scalar(@arrCharset)));
$strCode .= $arrCharset[$intRand];

5. Once the code was generated, check this with hashes of codes if exists. If exists deduct the counter of random codes we set in step #2, If not then write to hash. This will make the generation of codes unique.

if (exists($hshCodes{$strCode}))
{
    $i --;
}
else
{
    $hshCodes{$strCode} = 1;
    print "$strCode\n";
}

Please see below for the complete random unique code generator.

#!/usr/bin/perl

my @arrCharset = split //, "abcdefhjkmnpqrstuvwxyz2345678"; # 29 alphanumeric characters
my %hshCodes;
my ($i, $l, $strCode);

$intCodes = 540000; # this will generate 540,000 random codes.
$intCharCnt = 6; # this will generate 6 characters per code.

for ($i=1; $i<=$intCodes; $i++)
{
  $strCode = '';
  for ($l=1; $l<=$intCharCnt; $l++)
  {
    $intRand = int(rand(scalar(@arrCharset)));
    $strCode .= $arrCharset[$intRand];
  }

  if (exists($hshCodes{$strCode}))
  {
    $i --;
  }
  else
  {
    $hshCodes{$strCode} = 1;
    print "$strCode\n";
  }
}


1;

No comments:

Post a Comment