26 Feb
Posted by rdash as Perl tips, Programming, Parameters
Most Perl books start with a “Hello, World” tutorial. That’s probably the simplest example to start with for most programming languages. But finding out how many parameters are in the commandline to a Perl script is also simple, and very important to most of the tutorials on this site.
I should note beforehand that some Perl installations do not include the name of the Perl script as part of the parameter list, but some do. I will assume, unless otherwise noted, that it is not included.
Here is a Perl script to determine the number of commandline parameters:
#!/usr/bin/perl
####################
#
# FILE: params01.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
foreach my $parm (@ARGV)
{
print "parameter $i: ",$ARGV[$i],"\n";
$i++;
}
exit(0);
sub usage
{
print "Usage: perl params01.pl param01 [param02 ... param0n]\n";
}
This is the first in a series of Perl scripts dealing with mostly with data file manipulation. 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.
2 Responses
Randal L. Schwartz
March 3rd, 2006 at 11:42 am
1You’ve got $argc which seems to be the same as scalar @ARGV. You’ve got $i which seems to want to count up to $argc, but that’s also the same as counting up to scalar @ARGV. Except that you iterate over @ARGV directly. And then you don’t use $parm.
Very confusing code. And I oughta know… I’ve been in front of Perl beginners for more than a decade now.
rdash
March 3rd, 2006 at 2:22 pm
2Randal, thanks for the comments on each tutorial. These are extremely introductory Perl tutorials intended for people who’ve never used it. I was intending to ease up to the more powerful scripts that contain all kinds of system variables. But I think I have to take a new approach.
RSS feed for comments on this post · TrackBack URI
Leave a reply
Categories
Archives
Links
Meta
Calendar