Is this a challange? Oh boy, do I have some bad code that I've written. Of course, I know better nowadays. But back then... boy oh boy. Let me dig through my dead code archive for some examples.
Let's start with a nice subroutine to convert a decimal number to its binary form:
sub bin {
my $num = shift;
my $bin = "";
for my $digit (128, 64, 32, 16, 8, 4, 2, 1) {
if($num >= $digit) {
$num -= $digit;
$bin .= 1;
} else {
$bin .= 0;
}
}
return $bin;
}
The name is pretty bad to begin with, but the real problem is the brute-force algorithm. If only I'd known that I could've written it like this instead:
sub bin {
substr unpack("B*", pack "i", $_[0]), 0, 8;
}
Or even:
sub bin {
sprintf "%08b", $_[0];
}
Then of course, there's code like this, which just makes me shudder:
if(-e "$bmfile") {
&addlink("$bmfile","$url","$desc");
} else {
&newbmfile("$bmfile","$url","$desc");
}
Or how about this doozy:
LINE: foreach $line (@bmfile) {
chomp($line);
if($line =~ /title/i) {
($null,$title,$null) = split(/\<\/*title\>/i,$line);
} elsif($line =~ /a href/i) {
($null,$link,$null) = split(/\"/,$line,3);
($null,$desc) = split(/\>/,$line);
($desc,$null) = split(/\</,$desc);
} else { next LINE; }
if($link) { $links[$#links+1] = "$desc,$link"; }
}
Wait, wait! There's more!
while(defined($line = <IN>)) {
chomp($line);
@chunks = split(/\s+/,$line);
$ctr = 0;
while(defined($chunk = $chunks[$ctr])) {
if($chunk =~ /HREF/) {
($null,$url) = split(/\"/,$chunk);
print "$url\n";
@full = split(/\//,$url);
$dir = $full[5];
$file = $full[6];
system("wget $url");
unless(-e "$dir") { mkdir "$dir",0755; }
rename "$file","$dir/$file";
}
$ctr++;
}
}
I can keep going all day:
open(IN, "<$accesslog_file")
or die "Cannot open $accesslog_file for input: $!\n";
while(defined(my $line = <IN>)) {
chomp $line;
if($line =~ /(.*?) - - \[(.*?)\/(.*?)\/(.*?):(.*?):(.*?):(.*?) (
+.*?)\] \"(.*?)\" (.*?) (.*?)/) {
my $host = $1;
my $day = $2;
my $month = $3;
my $year = $4;
my $hour = $5;
my $minute = $6;
my $second = $7;
my $timezone = $8;
my $request = $9;
my $response = $10;
my $unknown = $11;
$host = &dns_lookup($host);
# push information into our hash
# adds a reference to the log entry array into
# the hash element for this host
push @{ $hosts{$host} }, [ $month, $day, $year,
$hour, $minute, "'$request'",
$response ];
}
}
close(IN);
So yeah. Now that I've let some of this stuff out there, and everyone thinks I'm a terrible coder, are you happy? Did I live up to your challenge? :-)