Source

hello / ocaml / grep.ml

Full commit
(*
  compile; 
  $ ocamlc str.cma grep.ml -o ogrep
  $ ./ogrep <pattern> <filename>
*)


let grep_file filterfunc filename =
  let fin = open_in filename in
  let grep_sub () =
    while true do
      let line = input_line fin 
      in if filterfunc line then output_string stdout (line ^ "\n")
(*	else output_string stdout ("fail" ^ line ^ " -\n") *)
    done
  in
    try grep_sub () with End_of_file -> close_in fin;;

let get_file_argv () = 
  match Array.to_list Sys.argv with
      [] -> []
    | _::tl ->
	match tl with
	    [] -> []
	  | _::files -> files ;;
	      
let main () = 
  let re = Str.regexp Sys.argv.(1) in
  let file_filter = fun infile-> grep_file (
    fun str-> 
      try let m = Str.search_forward re str 0 in m >= 0 
      with Not_found -> false
  ) infile
  in List.map file_filter (get_file_argv ());;

main();;