Pages

Arguments

We can pass arguments from the system command line to Perl. These arguments are made available to us by an array named @ARGV.

If we want to terminate our perl script in case no argument is passed, we could write something like this:
die "You passed no parameter\n" if not @ARGV;
A couple of things to say on this line:

Firstly, I used the so called statement modifier so common in Perl programming. The if check is after the statement that has to be executed in case of success. It looks wierd the first time, but after a while it gets kind of logical.

Secondly, @ARGV is used in a scalar context, so what we are cheching there is its size. The logical "not" operator, equivalent to the exclamation mark "!", negates the value. So, we can read the line in this way: terminate the program printing that message if no argument has been passed.

It is a matter of taste, we could have written equivalently:
die "You passed no parameter\n" unless @ARGV;
Counting on the fact that "unless" is a Perl synonym for "if not".

Once we ensured the array of arguments is not empty, we can print its elements in this way:
print "You passed ".@ARGV." arguments: @ARGV\n";
We uses a first time the @ARGV array in a scalar context, so we get the number of its elements, and then in a interpreted string, so we get all its elements separated by a blank.

If we want to print its elements in a more decorated way, we could use this piece of code:

foreach(@ARGV) {
print "'$_' ";
}
print "\n";

In Perl "for" and "foreach" are synonym. Besides, could be interesting notice the usage of the single quotes inside a double quoted string.

Say that we are expecting numeric values as input arguments, and we want to sum them all and then show the result to the user. We could do that in this way:

my $res;

for (@ARGV) {
$res += $_;
}
print "Sum: $res\n";

But we could use again a statement modifier, this time based on "for":

$res += $_ for @ARGV;
print "Sum: $res\n";

Chapter 4 of Beginning Perl by Simon Cozens is about loops and decisions.

No comments:

Post a Comment