It has been suggested that this article be merged into command-line argument. (Discuss) Proposed since May 2010. |
Different Command-line argument parsing methods are used by different programming languages to parse command-line arguments.
Programming languages
C
C uses argv
to process command-line arguments.[1]
Java
An example of Java argument parsing would be:
public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
Perl
Perl uses $ARGV
.
PHP
PHP uses argc
as a count of arguments and argv
as an array containing the values of the arguments.[2][3] 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;
}
Python
Python uses sys.argv
, e.g.:
for arg in sys.argv:
print arg
References
- ^ "The C Book — Arguments to main". Publications.gbdirect.co.uk. Retrieved 2010-05-31.
- ^ "PHP Manual". PHP. Retrieved 2010-05-31.
- ^ wikibooks:PHP Programming/CLI