Modulinos: Difference between revisions
Content added Content deleted
(→{{header|OCaml}}: more reasonable example using Sys.interactive) |
|||
Line 1,030: | Line 1,030: | ||
scriptedmain.ml |
scriptedmain.ml |
||
<lang ocaml> |
<lang ocaml>let meaning_of_life = 42 |
||
"exec" "ocaml" "str.cma" "$0" "$@" + let fi = 0 and exit _ _ = 0 in if false |
|||
then exit |
|||
fi |
|||
true else 0 |
|||
end;; |
|||
⚫ | |||
(* |
|||
Printf.printf "Main: The meaning of life is %d\n" |
|||
meaning_of_life |
|||
⚫ | |||
Interpret: |
|||
if not !Sys.interactive then |
|||
main ()</lang> |
|||
Invoked as a script: |
|||
⚫ | |||
<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: |
|||
... |
|||
⚫ | |||
⚫ | |||
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 main () = print_endline ("Main: The meaning of life is " ^ string_of_int meaning_of_life) |
|||
⚫ | |||
let program = Sys.argv.(0) |
|||
and re = Str.regexp "scriptedmain" in |
|||
try let _ = Str.search_forward re program 0 in |
|||
⚫ | |||
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}}== |
=={{header|Octave}}/{{header|MATLAB}}== |