Command Line Arguments
This page is under construction. Please come back later.
When running programs from the command line we have the option of supplying additional information in the form of arguments on the command line. Command line arguments take the form of strings separated by spaces. For example the following command line program invokation has three additional arguments.
$ perl Program.pl Fred 123 Flintstone
In our programs we can access each of these arguments using the variables
$ARGV[0]
, $ARGV[1]
, $ARGV[2]
, etc.
The first command line argument is in the variable with the 0 subscript. Additional arguments are in 1, 2, 3, etc.
#!/usr/bin/env perl use utf8; use Utils; use strict; use warnings; MAIN: { binmode(STDOUT, ":utf8"); binmode(STDERR, ":utf8"); binmode(STDIN, ":utf8"); foreach my $arg (@ARGV) { utf8::decode($arg); } print "Number of arguments: ", scalar(@ARGV), "\n"; print "Program Name: ", "CmdLineArgs1\n"; print "Arg 1: ", $ARGV[0], "\n"; print "Arg 2: ", $ARGV[1], "\n"; print "Arg 3: ", $ARGV[2], "\n"; print "Arg 4: ", $ARGV[3], "\n"; }
Output
If we want to treat a command line argument as a number we first need to convert from the string representation passed on the command line to a numeric type. This is where conversion functions come in handy. The example below illustrates how to convert command line arguments to integers.
#!/usr/bin/env perl use utf8; use Utils; use strict; use warnings; MAIN: { binmode(STDOUT, ":utf8"); binmode(STDERR, ":utf8"); binmode(STDIN, ":utf8"); foreach my $arg (@ARGV) { utf8::decode($arg); } my $a = Utils::stoiWithDefault($ARGV[0], 0); my $b = Utils::stoiWithDefault($ARGV[1], 0); my $c = $a + $b; print Utils::messageFormat("\{0:d\} + \{1:d\} = \{2:d\}", $a, $b, $c), "\n"; }
Output
The example below converts the command line arguments to floating point values.
#!/usr/bin/env perl use utf8; use Utils; use strict; use warnings; MAIN: { binmode(STDOUT, ":utf8"); binmode(STDERR, ":utf8"); binmode(STDIN, ":utf8"); foreach my $arg (@ARGV) { utf8::decode($arg); } my $a = Utils::stodWithDefault($ARGV[0], 0); my $b = Utils::stodWithDefault($ARGV[1], 0); my $c = $a + $b; print Utils::messageFormat("\{0:f\} + \{1:f\} = \{2:f\}", $a, $b, $c), "\n"; }
Output
Questions
- {{Who's on first?}}
- {{Who's on second?}}
- {{Who's on third?}}
Projects
More ★'s indicate higher difficulty level.
- Combined FICA Tax (Command Line Argument)
- Cubic Roots (Command Line)
- Dog Years (Command Line)
- Milky Way Stellar Density Estimate
- Quadratic Roots (Command Line)
References
- [[Perl Language Reference]]
- [[Comprehensive Perl Archive Network (CPAN)]]
- [[Beginning Perl]], Simon Cozens
- [[Perl Monks Tutorials]]