One of the strengths of Perl is that data types are very loose, and can change form. Thus programming variables can hold more than one type and shape of data, including numbers or strings. If you write prototype code to test out ideas, you can often temporarily assume that your input data is of the correct type, and leave error checking until later. Programmers of strongly-typed languages such as Java would flinch at such blasphemy, but for hardcore experienced programmers, we love this sort of flexibility because it’s so easy to write powerful prototype code, then add error checking code later. Our proof of concept can be produced in a matter of minutes instead of hours or days.

This tutorial is nothing grand, but is a setup for later tutorials. Here, we assume that the commandline parameters are all valid numbers, then generate the sum and the multiple of them. We use the @ARGV array/list variable, which contains the commandline parameters. This variable name originates from the C programming language, which Perl’s interpreter is written in. Keep in mind that this code assumes that your installation of Perl does not consider the Perl script name as a commandline parameter.

#!/usr/bin/perl
	
####################
#
# FILE: sum01.pl
#
####################
	
# 
	
use strict; # Declare strict checking on variable names, etc.
	
my $argc;   # Declare variable $argc. This represents
            # the number of commandline parameters entered.
	
$argc = @ARGV; # Save the number of commandline parameters.
if (@ARGV==0)
{
  # The number of commandline parameters is 0,
  # so print an Usage message.
  #
  usage();  # Call subroutine usage()
  exit();   # When usage() has completed execution,
            # exit the program.
}
	
print "Hello, there!\n";
print "You have $argc parameters\n";
	
my $i    = 0; # Declare and set a loop index
my $sum  = 0; # Initialize the sum variable
my $mult = 1; # Initialize the multiplication variable
	
foreach my $parm (@ARGV)
{
  my $value = $ARGV[$i];
  print "parameter $i: ",$value,"\n";
  $sum  += $value; # Same as $sum=$sum+$value;
  $mult *= $value; # Same as $mult=$mult*$value;
  $i++;
}
print "Sum of parameters: $sum\n";
print "Multiplication of parameters: $mult\n";
	
exit(0);
	
sub usage
{
  print "Usage: perl sum01.pl num1 [num2 ... numN]\n";
}

Personally, I wish Perl had a shorter notation for the summation and multiplication of an array, but it doesn’t. A much older language, APL (A Programming Language) used the notations +/A and x/A, respectively, where A is the array of numeric values. I doubt Perl will adopt such a notation, but you never know.

This is #2 in a series of Perl scripts. Please feel free to leave comments if there is something that you would like to see. I cannot guarantee that I’ll be able to answer immediately, but I will answer as soon as I can.

Technorati Tags: , , ,