For the past few days, I've been churning lines Perl codes, mostly parsers for various types of firewall and IDSes. At any time, the parser needs to parse anywhere from 60,000+ to a few hundred thousand lines of asskeys (more than 20MB file size) and insert them into a RDBMS, thus performance is really an issue. Interestingly enough, I found one piece of code that I wrote earlier this year that consumes so much CPU and memory, all because of one subroutine - converting dotted IP addresses to long format.
sub ip2long() {
$ip = shift(@_);
my @ips = split(/./,$ip);
foreach $tuple(@ips) {
$binNum = $binNum.dec2bin($tuple);
}
$BigNum = bin2dec($binNum);
return ($BigNum);
}
sub dec2bin {
my $str = unpack("B32", pack("N", shift));
$str =~ s/^0+(?=d)//;
my $RetStr = "";
for ($i=0; $i< 8 - length($str); $i++) {
$RetStr=$RetStr."0";
}
$RetStr = $RetStr.$str;
return $RetStr;
}
sub bin2dec {
return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}
Absolute murder! I don't know why I was so naive, but the fix is the following:
sub ip2long {
$ip = shift(@_);
@arr = split(/./,$ip);
foreach $a (@arr) {
$longIP < <= 8;
$longIP |= $a;
}
return $longIP;
}
Just another day in coding-land.
Listening to: Too Phat - Anak Ayam