# -*- d -*- # smallest # the smallest running program doing nothing void main() {} # hello world # print a simple string on stdout import std.stdio; void main() { write("Hello World"); } # argv # access command line parameters (no segmentation fault accepted, nor silent exception, so some languages must explicitly check the presence of the argument) import std.stdio; void main(string[] a) { if(a.length>1) writeln(a[1]); } # env # access environment variable import std.stdio,std.process; void main() { writeln(getenv("HOME")); } # test file exists # return exit code error (non zero) if a file does not exist import std.file; int main() { return !exists("/etc/mtab"); } # test file readable # return exit code error (non zero) if a file is not readable import std.stdio; void main() { File("/etc/mtab"); } # formatting # print integers in a simple formatted string import std.stdio; void main() { int a=1,b=2; writeln(a," + ",b," = ",a+b); } # system # call an external program and check the return value import std.stdio,std.process; void main() { if (system("false")) stderr.writeln("false failed"); system("echo done"); } # sed in place # remove #-comments from a file (modifying the file, i.e. in place) import std.file,std.regex; void main(string[] a) { a[1].write(a[1].readText().replace(regex("#.*","g"),"")); } # compile what must be # find and compile .c files into .o when the .o is old or absent import std.stdio,std.file,std.process; void main() { foreach (c; listdir("","*.c")) { auto o = c[0..$-1]~'o'; if (lastModified(o,0) < lastModified(c)) { writeln("compiling "~c~" to "~o); system("gcc -c -o '"~c~"' '"~o~"'"); } } } # grep # grep with -F -i -h handling, usage, grep'ing many files import std.stdio,std.regex,std.getopt; int main(string[] a) { bool h,F,i; getopt(a,"h",&h,"F",&F,"i",&i); if (a.length<2 || h) { writeln("usage: grep [-F] [-i] regexp [files...]"); return 1; } auto e = F ? a[1].replace(regex(r"\W","g"),r"\$&") : a[1]; foreach (f; a[2..$]) foreach (l; File(f).byLine()) if (!l.match(regex(e, i ? "i" : "")).empty) writeln(a.length>3 ? f~':'~l : l); return 0; }