PDA

View Full Version : Help with enclosed code - Simple


drunkagain
10-23-2005, 03:27 PM
Hi:

I found some code that will give me a very unique number. I think it gets the process ID/number, IP address, and date/time. It does everything I want except 1 little thing. The first part of the number varies. Sometimes it is 4 digits, sometimes it is 5 digits. Because I parse the number in a database, I need the numbers to be standarized. Can anyone help me with the following.

Add a zero (0) to the front of the first number, then give me the 5 right most digits. Example:

51345 becomes 051345 which finally becomes 51345
4287 becomes 04287 which finally becomes 04287

************* Code *************************

$ip=$ENV{'REMOTE_ADDR'};

chomp ($ip); #remove any carriage returns.
($var1,$var2,$var3,$var4) = split(/\./,$ip);

if(length($var1)==1){$var1="00".$var1;}
if(length($var1)==2){$var1="0".$var1;}
if(length($var2)==1){$var2="00".$var2;}
if(length($var2)==2){$var2="0".$var2;}
if(length($var3)==1){$var3="00".$var3;}
if(length($var3)==2){$var3="0".$var3;}
if(length($var4)==1){$var4="00".$var4;}
if(length($var4)==2){$var4="0".$var4;}

$ip=$var1.$var2.$var3.$var4;

$unique_customer_id = $$ . "-" . $ip . "-" . time();

************* Code *************************

Thanks

FishMonger
10-23-2005, 04:44 PM
It would be much cleaner and better to use a single sprintf statement instead of all of those if blocks.
$ip = $ENV{'REMOTE_ADDR'};

chomp ($ip); #remove any carriage returns.

($var1,$var2,$var3,$var4) = split(/\./,$ip);
$unique_customer_id = sprintf("%05d-%03d%03d%03d%03d-%d", $$, $var1,$var2,$var3,$var4, time());

print $unique_customer_id;
In my test, given an assigned ip address of:
$ip = '10.16.5.63';
produced this:
02508-010016005063-1130082103

FishMonger
10-23-2005, 04:54 PM
If you want, you could even do the split within the sprintf statement.

$unique_customer_id = sprintf("%05d-%03d%03d%03d%03d-%d", $$, split(/\./,$ip), time());

You can even put the $ENV{'REMOTE_ADDR'} into the sprintf statement which reduces your code down to 1 line!

$unique_customer_id = sprintf("%05d-%03d%03d%03d%03d-%d", $$, split(/\./, $ENV{'REMOTE_ADDR'}), time());