(* -*- caml -*- *) (* hello world *) (* print a simple string on stdout *) print_endline "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) *) print_endline Sys.argv.(1) (* env *) (* access environment variable *) print_endline(Sys.getenv "HOME") (* test file exists *) (* return exit code error (non zero) if a file does not exist *) if not(Sys.file_exists "/etc/mtab") then exit 1 (* test file readable *) (* return exit code error (non zero) if a file is not readable *) try open_in("/etc/mtab") with _ -> exit 1 (* formatting *) (* print integers in a simple formatted string *) let a, b = 1, 2 in Printf.printf "%d + %d = %d\n" a b (a + b) (* system *) (* call an external program and check the return value *) if Sys.command "false" != 0 then prerr_endline("false failed"); ignore(Sys.command "echo done") (* sed in place *) (* remove #-comments from a file (modifying the file, i.e. in place) *) let l = Std.input_list (open_in Sys.argv.(1)) in let f = open_out Sys.argv.(0) in List.iter (fun l -> output_string f ((Str.replace_first (Str.regexp "#.*") "" l) ^"\n")) l;; (* compile what must be *) (* find and compile .c files into .o when the .o is old or absent *) open Unix let listdir dir = let rec listdir_ hdir = try let s = readdir hdir in if s = "." || s = ".." then listdir_ hdir else s :: listdir_ hdir with End_of_file -> [] in let hdir = opendir dir in let l = listdir_ hdir in closedir hdir ; l let rec doit dir = List.iter (fun s -> let f = Filename.concat dir s in if (lstat f).st_kind = S_DIR then doit f else if Filename.check_suffix f ".c" then let o = Filename.chop_extension f ^ ".o" in if not (Sys.file_exists o && (stat o).st_mtime > (stat f).st_mtime) then let cmd = Printf.sprintf "gcc -c -o '%s' '%s'" o f in print_endline ("compiling " ^ f ^ " to " ^ o) ; ignore (Sys.command cmd) ) (listdir dir) ;; doit(".") (* grep *) (* grep with -F -i -h handling, usage, grep'ing many files *) open List let rec iter_lines f fd = try f (input_line fd) ; iter_lines f fd with End_of_file -> () let _ = let i, fixed, usage = ref false, ref false, ref false in Arg.parse [ "-i", Arg.Set i, "" ; "-F", Arg.Set fixed, "" ; "-h", Arg.Set usage, "" ; ] (fun _ -> ()) "" ; match filter (fun s -> s.[0] <> '-') (Array.to_list Sys.argv) with | _ :: r :: files when not !usage -> let r = if !fixed then Str.quote r else r in let re = (if !i then Str.regexp_case_fold else Str.regexp) r in let prefix = length files > 1 in iter (fun (name, fd) -> iter_lines (fun s -> try let _ = Str.search_forward re s 0 in print_endline ((if prefix then name ^ ":" else "") ^ s) with Not_found -> () ) fd ) (if files = [] then ["", stdin] else map (fun s -> s, open_in s) files) | _ -> prerr_endline "usage: grep [-F] [-i] regexp [files...]" ; exit 1