Parse command-line arguments: Difference between revisions
Content added Content deleted
(Add implementation in Standard ML (SML/NJ and MLton)) |
|||
Line 676: | Line 676: | ||
println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}") |
println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}") |
||
}</lang> |
}</lang> |
||
=={{header|Standard ML}}== |
|||
{{works with|SML/NJ}} |
|||
{{works with|MLton}} |
|||
The following code listing can be compiled with both [[SML/NJ]] and [[MLton]]: |
|||
<lang sml>structure Test = struct |
|||
exception FatalError of string |
|||
fun main (prog, args) = |
|||
(let |
|||
exception Args |
|||
val switch = ref false |
|||
fun do_A arg = print ("Argument of -A is " ^ arg ^ "\n") |
|||
fun do_B () = if !switch then print "switch is on\n" else print "switch is off\n" |
|||
fun usage () = print ("Usage: " ^ prog ^ " [-help] [-switch] [-A Argument] [-B]\n") |
|||
fun parseArgs nil = () |
|||
| parseArgs ("-help" :: ts) = (usage(); parseArgs ts) |
|||
| parseArgs ("-switch" :: ts) = (switch := true; parseArgs ts) |
|||
| parseArgs ("-A" :: arg :: ts) = (do_A arg; parseArgs ts) |
|||
| parseArgs ("-B" :: ts) = (do_B(); parseArgs ts) |
|||
| parseArgs _ = (usage(); raise Args) |
|||
in |
|||
parseArgs args handle Args => raise FatalError "Error parsing args. Use the -help option."; |
|||
(* Do something; *) |
|||
OS.Process.success |
|||
end) |
|||
handle FatalError e => (print ("Fatal Error:\n"^e^"\n"); OS.Process.failure) |
|||
end |
|||
(* MLton *) |
|||
val _ = Test.main (CommandLine.name(), CommandLine.arguments())</lang> |
|||
=== SML/NJ === |
|||
[[SML/NJ]] can compile source code to a "heap file", witch can than be executed by the interpreter with arguments given (see [http://stackoverflow.com/questions/5053149/sml-nj-how-to-compile-standalone-executable this entry on stackowerflow.com] for more information). |
|||
The <code>source.cm</code> file should lock like this: |
|||
<lang>Group |
|||
is |
|||
SOURCE_FILE.sml |
|||
$/basis.cm</lang> |
|||
To compile the program, use <code>ml-build sources.cm</code>. This should create a "heap file" <code>sources.x86-linux</code>, depending on your architecture. |
|||
The heap file can be executed with <code>sml @SMLload=sources.x86-linux ARGUMENTS</code>, or the script [http://www.smlnj.org/doc/heap2exec/index.html <code>heap2exec</code>] can be used to make a single executable. |
|||
=== MLton === |
|||
[[MLton]] compiles the source file directly to a executable by invoking <code>mlton SOURCE_FILE.sml</code>. |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |