PDA

View Full Version : Modifying the IP number format with zero's


id10error
02-18-2005, 06:56 AM
Hi:

I am trying to create a very unique ID number. The code at the bottom works perfectly. What I really need is to modify the IP information (format) a bit for my database. Single digit numbers need to have 2 zero's in front of the number, double digit numbers need to have 1 zero in front of the number and triple digit numbers need not to be changed. Also, remove ALL the . (dot) and squeeze the numbers together.


Example:

IP 125.15.3.113

change to

125015003113

My Code:
$unique_customer_id = $$ . "-" . $ENV{'REMOTE_ADDR'} . "-" . time();


Can anyone help me with this please?


TIA

mlseim
02-18-2005, 04:27 PM
Well, this isn't pretty, but ... :o

Perl's specialty is string manipulation, but I sort of did it the long way.
Someone more "Perl Expert" than me can probably provide a string
method that takes less lines of code.

But, here it is (it works):
========================================================

#!/usr/bin/perl

$ip="125.15.3.113"; #start out with this.

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

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; #combine the 4 numbers.

print "Content-type: text/html\n\n";
print $ip;

Puffin the Erb
02-18-2005, 10:26 PM
Here's another possible way:

my @parts = split(/\./,$ip);
my $parts;
my $result;

my $count = scalar(@parts);
for(my $i=0;$i<$count;$i++)
{
$parts[$i]=sprintf("%03s",$parts[$i]);
$result .= $parts[$i];
}