Its been such a long time that I never wrote a single program in one of the language I love : Perl. So I was going through questions posted on Microsoft interview list and I decided to write the program in Perl.
The question was : “Write an efficient C code for ‘tr’ program. ‘tr’ has two command line arguments. They both are strings of same length. tr reads an input file, replaces each character in the first string with the corresponding character in the second string. eg. ‘tr abc xyz’ replaces all ‘a’s by ‘x’s, ‘b’s by ‘y’s and so on.”
And the code in Perl is as follows (comments for prints are suppressed and can be used for debugging purposes) :
#!/usr/bin/perl
my %hash = ();
if($#ARGV + 1 != 3){
print “usage : ./tr.pl <search> <replace> <file>\n”;
exit;
}
if(length($ARGV[0]) != length($ARGV[1])){
print “search and replace pattern have to be os same length\n”;
exit;
}
my($search) = $ARGV[0];
my($replace) = $ARGV[1];
my($file) = $ARGV[2];
#print “$search : $replace : $file\n”;
prepareHash();
modifyHash($search, $replace);
readFile($file);
sub prepareHash(){
my(@array) = (a .. z);
#print “@array\n”;
foreach(@array){
$hash{$_} = $_;
}
#while(my($key,$value) = each %hash){
# print “$key => $value, “;
#}
}
sub modifyHash(){
my(@search) = split(//,$_[0]);
my(@replace) = split(//,$_[1]);
#print “@search\n”;
#print “@replace\n”;
foreach($i = 0; $i < scalar(@search); $i ++){
$hash{$search[$i]} = $replace[$i];
}
#while(my($key,$value) = each %hash){
# print “$key => $value, “;
#}
#print “\n”;
}
sub readFile(){
print “opening file ..\n”;
my($buf,$data,$n);
open(FILE,”$file”) or die “couldn’t open the file : $!”;
while(($n = read FILE,$data,1) != 0){
#print “$data:$hash{$data}, “;
print “$data”;
if(!$hash{$data}){
$buf .= $data;
}else{
$buf .= $hash{$data};
}
}
print “\nAfter replacement ..\n”;
print “$buf”;
}
output :
./tr.pl abcmno xyzpqr text
opening file ..
a b c d e f g h i j k l m n o p q r s t u v w x y z
After replacement ..
x y z d e f g h i j k l p q r p q r s t u v w x y z
