Pure Programmer
Blue Matrix


Cluster Map

Command Line Arguments

L1

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.

CmdLineArgs1.pl
#!/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
$ perl CmdLineArgs1.pl Fred Barney Wilma Betty Number of arguments: 4 Program Name: CmdLineArgs1 Arg 1: Fred Arg 2: Barney Arg 3: Wilma Arg 4: Betty $ perl CmdLineArgs1.pl Φρειδερίκος Барнеи ウィルマ 贝蒂 Number of arguments: 4 Program Name: CmdLineArgs1 Arg 1: Φρειδερίκος Arg 2: Барнеи Arg 3: ウィルマ Arg 4: 贝蒂

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.

CmdLineArgs2.pl
#!/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
$ perl CmdLineArgs2.pl 326 805 326 + 805 = 1131

The example below converts the command line arguments to floating point values.

CmdLineArgs3.pl
#!/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
$ perl CmdLineArgs3.pl 3.21 7.01 3.210000 + 7.010000 = 10.220000

Questions

Projects

More ★'s indicate higher difficulty level.

References