Recently, I was porting some code from Perl to Java. There was a huge snippet of code in Perl in which a hash was defined and data was being added to it. I had to use the same data in my Java code also. This was around 80 lines of code.

To give an example :
From
$abrv{av} = ‘avenue’;
to
abbrevationsMap.put(“av”, “avenue”);

I messed around with Eclipse search/replace for sometime to do the transformation but could not get it done. I copied the 80 lines to a file. Opened up gvim and wrote the below script to do the transformation.

open(RH, "<foo.txt");
open(WH, ">bar.txt");

while () {
	chop:
	$_ =  &sanitise($_);
	next if $_ eq "";
	print WH $_;
}

sub sanitise {
	my $string = shift;
	if ($string =~ m/^#/) {
		return "";
	}

	$string =~ s/\$abrv/abbrevationsMap.put/;
	$string =~ s/'/"/g;
	$string =~ s/;/);/g;
	$string =~ s/\{/("/;
	$string =~ s/}/",/;
	$string =~ s/\s+=//;
	return $string;
}

I can hear people scream “I can do the same thing in Java”, etc etc. I totally agree with you folks, but you can do the same in Perl in less lines of code without using a heavy weight IDE.

Advertisements