Here we go again... get involved in a very serious discussion about a not-so-important subject. So what? I'm also bored here...
Generally it's a good programming practice to separate data from the code. Putting the country codes list in a text file makes it easier to maintain (update) the info without having to touch the code. Hint: I'm not talking about speed, I'm talking about flexibility.
But for some reason I always prefer a shell script.Code:# showcountry.pl open(FIN, "countrycodes.txt"); while(<FIN>) { chomp; ($code, $country) = split(/\s/, $_); if ($code eq $ARGV[0]) { print "$country\n"; last; } }
And as a bonus...Code:# showcountry.sh awk -v code=$1 '{ if ($1 == code) print $2 }' countrycodes.txt # showcountry2.sh grep $1 countrycodes.txt | cut -f2
Of course there should be a tab separated text file named countrycodes.txt in current directory.Code:// showcountry.c #include <stdio.h> #include <string.h> char *find(const char *str) { FILE *fp; static char line[80]; if (fp = fopen("countrycodes.txt", "r")) { while (fgets(line, 80, fp)) if (strstr(line, str)) return line; fclose(fp); } line[0] = 0; return line; } char *showcol2(char *str) { char *token; char *delim = "\t"; // this is a tab in quotes static char result[80]; token = strtok(str, delim); token = strtok(NULL, delim); if (token) strcpy(result, token); return result; } int main(int argc, char *argv[]) { puts(showcol2(find(argv[1]))); }
Oh well I guess we all have too much time in our hands...
Peace always,
<jdenny>






Reply With Quote