Command-line argument parsing
Encyclopedia
Different Command-line argument parsing methods are used by different programming languages to parse command-line arguments.

C

C uses argv to process command-line arguments.

Java

An example of Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 argument parsing would be:

public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}

PHP

PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

 uses argc as a count of arguments and argv as an array containing the values of the arguments. To create an array from command-line arguments in the -foo:bar format, the following might be used:


$args = parseArgs( $argv );
echo getArg( $args, 'foo' );

function parseArgs( $args ) {
foreach( $args as $arg ) {
$tmp = explode( ':', $arg, 2 );
if( $arg[0] "-" ) {
$args[ substr( $tmp[0], 1 ) ] = $tmp[1];
}
}
return $args;
}

function getArg( $args, $arg ) {
if( isset( $args[$arg] ) ) {
return $args[$arg];
}
return false;
}


PHP can also use getopt

Python

Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 uses sys.argv, e.g.:

import sys
for arg in sys.argv:
print arg

Racket

Racket uses a current-command-line-arguments parameter, and provides a racket/cmdline library for parsing these arguments. Example:
  1. lang racket

(require racket/cmdline)
(define smile? #true)
(define nose? #false)
(define eyes ":")
(command-line
#:program "emoticon"
#:once-any ; the following two are mutually exclusive
[("-s" "--smile") "smile mode" (set! smile? #true)]
[("-f" "--frown") "frown mode" (set! smile? #false)]
#:once-each
[("-n" "--nose") "add a nose" (set! nose? #true)]
[("-e" "--eyes") char "use for the eyes" (set! eyes char)])
(printf "~a~a~a\n" eyes (if nose? "-" "") (if smile? ")" "("))

The library parses long and short flags, handles arguments, allows combining short flags, and handles -h and --help automatically:

$ racket /tmp/c -nfe 8
8-(
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK