Archive for July, 2008

Creating a map of maps in Java

Posted in Java with tags , , , on July 30, 2008 by vinaychilakamarri

At times I saw that some people get struck when it comes to creating a map of maps. It is not really a rocket science but needs a little sleight of hand. Here I will explain on how to create a map of maps in Java language. The same can be used for other languages. Also post in some of the other cool tricks if you may have any:

Here is the scenario… I have a text file in this format:

Gasoline Mexico $2.5

Gasoline USA $4.5

Gasoline Afghanistan $85

Beer Mexico $1.25

Beer USA $2.85

Beer Afghanistan $0.0

Now I want to query for ‘gasoline’ and get a map of all ‘country —> price’ listings. Similarly, I want to ask for beer and get a list of ‘country —> price’. This can be easily done by building a hashmap of hashmaps. As a visual guide, this is how the Datastructure will look like, after we’re done designing it:

My Approach:

Hashmap<String,Properties> gasBeerMap = new HashMap<String,Properties>();

//read the text file, get the inputstream

while(there are more lines in the textfile)


String[] tokens = tokenize the line;

Properties tmp = (Properties) gasBeerMap.get(tokens[0]);

if(tmp == null)


tmp = new Properties();




This will check if the map for a specific entry is null. If it is, then it will insert a new map to that specific entry as it’s mapped value. As it can be observed, for the next iterations, the map will only get updated. This is one approach to the problem. Let me know if you have some cool approaches to this problem


Exporting your Java project to a jar file in two clicks using Fat-jar plugin

Posted in eclipse, Java with tags , , , , , on July 29, 2008 by vinaychilakamarri

Sick and tired of writing manifest files and arranging jar files and class files, I searched to see if I can find some click-click-click eclipse feature that will do this job for me. And the answer came in after a brief googling: The fat-jar plugin. Installing this plugin’s zip is easy. Extract the zip to some place and copy the folder under ‘plugins’ to the actual eclipse plugins directory. Restart the eclipse and you should see a ‘Build Fat jar’ with a green cross when you right click on your project. Here is the tutorial on how to build the jar file after you are done with the plaugin installation:

Happy jar building!

Subtle things in perl part 2: The difference between ‘or’ and ||

Posted in Perl on July 27, 2008 by vinaychilakamarri

In perl, both ‘or’ and || mean the same thing. But they act in different ways when used in certain circumstances. For example, lets say we are trying to open a file for read and write operations. It’s always a good idea to handle the IO errors and we do this in the following way:

$file = shift;
open FILE, $file or die “Couldn’t open the file $file”; #note this

The second step can also be written in this way:
open FILE, $file || die “Couldn’t open the file $file”; #note this

But when the execution of this program happens, you will never see the message in ‘die’, if you use a || instead of ‘or’. Reason for this is that the || operator has a precedence level higher than that of ‘or’ and since
the ‘open FILE, $file’ returns a value after an attempt to execute, the || is always true and die is never reached

The actual reason as Martin, one of the commentators  puts it,

The actual reason is that the operator precedence for the double pipe is higher than the comma, so perl is resolving the double pipe first, which chooses the first true result of its two parameters, in this case $file and the die statement. As long as $file is a nonempty string it counts as true and always gets returned by the double pipe.

So it is always advisable to use ‘or’ instead of ||. If you want to use ‘||’, you can do it by using the
pen file with parathesis which ensures the precedence of the operators.

open (FILE, $file) || die “Couldn’t open the file $file”;

Playing with shift , @_ , $_

Posted in Perl on July 22, 2008 by vinaychilakamarri

The ‘Shift’ function pops the first element of an array and returns the popped item to the left side variable. There is a way to write cryptic code with “shift”, to impress your family (yep.. only family, sorry). Perl has some internal default variables that get initialized when in some sub routine. Lets say you’re passing an array of elements to some sub routine. You don’t need an explicit variable like in some languages to store that passed variable. You can directly use the implicit variables for getting the passed parameters. Let’s write a subroutine using some implicit variables and “shift”:

sub printFileContent {


printInsideThings ($_);

sub printInsideThings {
open FILE,$_;
while($line = <FILE>){
print $line;

printFileContent (“C:\\Data\\virtual-hosting-howto.html”,”C:\\Data\\virtual-boasting-howto.html”);

As I pass a list of files, the ‘@_’ of my first sub is already initialized with the list of strings that I passed.
So I used ‘foreach’ and passed the “$_” to another subroutine. The ‘$_’ will be initialized to the list item for
each iteration over the list. The other sub takes the string, and using a ‘$_’, which is initialized with the passed value by default, it opens the file and initializes a global variable ‘FILE’ and prints the content line by line in the while loop. The ‘< >’ opens the file and reads it line by line for you (uber cool tool eh?). Other ways we can do the later subroutine:

sub printInsideThings {
open FILE,shift;
print ;

Look at the while loop there. Perl uses the ‘$_’ so implicitly that you don’t even have to specify it. That loop initializes the ‘$_’ for every iteration and assigns it the line it reads from the file. The “print;” is equivalent to “print $_;” Again, the ‘shift’ in that file opener takes out the first of the ‘@_’ and passes it for parsing stuff

This one prints the contents of a single file that is passed:

sub openFu{
open FILE, shift;

openFu “c:\\data\\virtual-hosting-howto.html”;

Subtle things in perl

Posted in Perl on July 13, 2008 by vinaychilakamarri

There are some untold things in Perl, that really caught my attention. Firstly, we can assign an array to a scalar variable. Doing so will initialize that scalar to the size of that array. There is also an explicit function for this. Here is what I am talking about:

@arr = qw(i can be a bad guy);

$var = @arr;

print “$var”;

This will print 6. In the same way we can also use an inbuilt function for this. The function is called ‘scalar’

$var = scalar(@arr); assigns the size of the array. In the same way we can also initialize a variable to a list. But the variable will get initialized to the last variable of that list. For example:

$var = (1,2,3,4); will initialize $var to 4.

Pyramid in perl

Posted in Perl on July 6, 2008 by vinaychilakamarri

Lets say you want to print something like this:

Here is the code I wrote:

# !/usr/bin/perl
@array = (‘A’ .. ‘Z’);
$in = <>;
if($in < 0)
print “Can’t proceed”;
for($i = 0 ; $i < $in ; $i++)
@tmp = (”);
for($k = scalar(@array); $k > $i; $k–)
print ” “;
for($j = 0 ; $j < $i; $j++)
print “@array[$j]”;
@revtmp = reverse(@tmp);
{ print “$_” ;}
print “\n”;

This is a rough attempt at the problem. It can be:
1. Checked for input validity

2. Enhanced with what ever you want to ice on top of it.

Have fun!

Copying and deleting files in multiple directories with perl.

Posted in Perl with tags , , on July 1, 2008 by vinaychilakamarri

Now I came out with a simple program for doing this. I was faced with a situation where I had to copy a file in 20 different folders in order to test some code that I was writing. I also had to change data and copy the file again many times. I figured that this process would kill me. I wanted to automate this process so that i don’t have to struggle further. Initially I played with Batch scripting.. never liked it ­čśŽ And all of sudden I remembered about my old time dabbling with perl.. now that flash of idea came in as a real perl from the sky!. Here is the code:

print “Which file to copy: “;
$fl = <>;
use File::Copy;
opendir DIR, “.”; # . is the current directory

while ( $filename = readdir(DIR) )
if(-d $filename && $filename ne ‘.’ && $filename ne ‘..’)
print “Copied $fl to: ” , $filename,”\n”;

Here I list the directories using ‘opendir’ on the current directory (here is where my 20 folders were). You could also take an input for this from the user. And for each item in the list returned, I copy the file in that directory with a ‘copy’ function. I filtered the “.”, “..” from the list for I don’t need to copy my files there. The “-d” checks for directory.

In the same manner, we can also delete files from the directories:

print “Which file to delete: “;
$fl = <>;
opendir DIR, “.”; # . is the current directory

while ( $filename = readdir(DIR) )
if(-d $filename && $filename ne ‘.’ && $filename ne ‘..’)
print “Deleted $fl in: ” , $filename,”\n”;

#observer the unlink function here. You have to specify the path of the file for each iteration. “\\” is a slash with an escape.