Modulinos: Difference between revisions

→‎{{header|OCaml}}: more reasonable example using Sys.interactive
(→‎{{header|OCaml}}: more reasonable example using Sys.interactive)
Line 1,030:
scriptedmain.ml
 
<lang ocaml>if true then ignore begin let kkkk _ _ _ _ _meaning_of_life = 0 in kkkk42
"exec" "ocaml" "str.cma" "$0" "$@" + let fi = 0 and exit _ _ = 0 in if false
then exit
fi
true else 0
end;;
 
let main () =
(*
Printf.printf "Main: The meaning of life is %d\n"
meaning_of_life
 
let _() =
Interpret:
if not !Sys.interactive then
main ()</lang>
 
Invoked as a script:
./scriptedmain.ml
 
<lang sh>$ ocaml scriptedmain.ml
Compile:
Main: The meaning of life is 42</lang>
 
Loaded into an ocaml toplevel/utop:
ocamlc -o scriptedmain -linkall str.cma scriptedmain.ml
 
<lang>$ ocaml
Run:
...
./# #use "scriptedmain.ml";;
letval meaning_of_life : int = 42
val main : unit -> unit = <fun>
# meaning_of_life;;
- : int = 42
# </lang>
 
The limit of this technique is "avoiding running something when loading a script interactively". It's not applicable to other uses, like adding an example script to a file normally used as a library, as that code will also fire when users of the library are run.
./scriptedmain
 
*)
 
let meaning_of_life : int = 42
 
let main () = print_endline ("Main: The meaning of life is " ^ string_of_int meaning_of_life)
 
let _ =
let program = Sys.argv.(0)
and re = Str.regexp "scriptedmain" in
try let _ = Str.search_forward re program 0 in
main ()
with Not_found -> ()</lang>
 
test.ml
 
<lang ocaml>if true then ignore begin let kkkk _ _ _ _ _ _ = 0 in kkkk
"exec" "ocaml" "str.cma" "scriptedmain.cmo" "$0" "$@" + let fi = 0 and exit _ _ = 0 in if false
then exit
fi
true else 0
end;;
 
(*
 
Compile:
 
ocamlc -o test -linkall str.cma scriptedmain.ml test.ml
 
Interpret:
 
./test.ml
 
Run:
 
./test
 
*)
 
let main () = print_endline ("Test: The meaning of life is " ^ string_of_int Scriptedmain.meaning_of_life)
 
let _ =
let program = Sys.argv.(0)
and re = Str.regexp "test" in
try let _ = Str.search_forward re program 0 in
main ()
with Not_found -> ()</lang>
 
=={{header|Octave}}/{{header|MATLAB}}==
Anonymous user