bearophile napisał(a):

Nice page. I submitted some "scripts" so D will be featured on it.
You may show them here too.

Good idea. I must say it was fun writing "scripts" in D. They could use community sandblasting before publishing. Remember, the aim is to write the smallest program possible, so optimize character count (contiguous whitespaces count as 1).

smallest - the smallest running program doing nothing:
void main(){}

hello world - print a simple string on stdout:
import std.stdio;
void main(){writeln("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;writefln("%s + %s = %s",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"); writeln("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)) {
            writefln("compiling %s to %s",c,o);
            system("gcc -c -o '"~c~"' '"~o~"'");
        }
    }
}

grep - grep with -F -i -h handling, usage, grep'ing many files:
import std.stdio,std.array,std.regex;
int main(string[] a){
    auto o=["-h":0,"-F":0,"-i":0];
    while(!(a=a[1..$]).empty) {
        if(auto b=a[0] in o) *b=1;
        else break;
    }
    if(!a.length||o["-h"]){
        writeln("usage: grep [-F] [-i] regexp [files...]");
        return 1;
    }
    auto e=o["-F"]?a[0].replace(regex(r"\W","g"),r"\$&"):a[0];
    foreach(f;a[1..$])
        foreach(l;File(f).byLine())
            if(!l.match(regex(e,o["-i"]?"i":"")).empty)
                writeln(f,':',l);
    return 0;
}

--
Tomek

Reply via email to