# -*- erlang -*- # smallest # the smallest running program doing nothing main(_) -> ok # hello world # print a simple string on stdout main(_) -> io:fwrite("hello world\n"). # argv # access command line parameters (no segmentation fault accepted, nor silent exception, so some languages must explicitly check the presence of the argument) main([Arg|_]) -> io:format("~s~n", [Arg]). # env # access environment variable main(_) -> io:format("~s~n", [os:getenv("HOME")]). # test file exists # return exit code error (non zero) if a file does not exist main(_) -> case filelib:is_file("/etc/mtab") of true -> ok; _ -> erlang:halt(1) end. # test file readable # return exit code error (non zero) if a file is not readable main(_) -> case file:read_file("/etc/mtab") of {ok, _} -> ok; _ -> erlang:halt(1) end. # formatting # print integers in a simple formatted string main(_) -> A = 1, B = 2, io:fwrite("~p + ~p = ~p~n", [A, B, A+B]). # system # call an external program and check the return value main(_) -> case os:cmd("false; echo $?") of [$0|_] -> ok; _ -> io:fwrite("false failed~n") end, io:fwrite(os:cmd("echo done")). # sed in place # remove #-comments from a file (modifying the file, i.e. in place) main([F|_]) -> {ok, B} = file:read_file(F), Lines = string:tokens(erlang:binary_to_list(B), "\n"), Not_comment = fun ($#) -> false; (_) -> true end, New = lists:map( fun(Line) -> L = lists:takewhile(Not_comment, Line), L ++ "\n" end, Lines ), file:write_file(F, erlang:list_to_binary(New)). # compile what must be # find and compile .c files into .o when the .o is old or absent main(_) -> Fun = fun (Cfile, Acc) -> [$c | File] = lists:reverse(Cfile), Ofile = lists:reverse([$o | File]), case is_compile_time(Cfile, Ofile) of true -> io:format("compiling ~s to ~s~n", [Cfile, Ofile]), os:cmd(io_lib:format("gcc -c -o ~s ~s~n", [Ofile, Cfile])), [Ofile | Acc]; false -> Acc end end, Regexp = regexp:sh_to_awk("*.c"), cc_recurse('.', Regexp, Fun). is_compile_time(C, O) -> case filelib:is_file(O) of true -> filelib:last_modified(C) > filelib:last_modified(O); false -> true end. cc_recurse(Directory, Regexp, CC_Fun) -> catch filelib:fold_files(Directory, Regexp, false, CC_Fun, []), {ok, Files} = file:list_dir(Directory), lists:foreach( fun (Subdir) -> cc_recurse(Subdir, Regexp, CC_Fun) end, lists:filter(fun (File) -> filelib:is_dir(File) end, Files) ).