This article details how to read command-line parameters in a Perl script.
DL» read_cmdline.zip
Reading Command-line Parameters
Quite often, it is necessary to have a script take user-defined data from the
commnd-line. This allows a script to be more portable for different uses since
certain variables are not hard-coded. This task is quite simple in Perl. All
command-line parameters are read into an array of arguments. A specific command-line
parameter is referenced by it's position in the array.
Typically, the first thing I do when writing a script that will take command-line
parameters is determine how many parameters are needed and the rules needed to
determine if the values presented are valid. Before trusting any data, it should be
checked for validity. This helps prevent unexpected behaviour in a script that may take
time to isolate the actual cause of the problem.
For this example, we will have the following rules:
- The script will only accept one command-line parameter.
- The command-line parameter must be in the format --infile=<ini_text_file>
- The file name specified must be greater than 2 characters and less than 256 characters in length.
Any violation of these rules will cause the script to exit with an error. If all the checks pass,
the script will print the file name to the console. These do not verify the existence of the file or
if the account space the script is using has permission to read the file. This level of error-checking
would be handled by the file I/O routine.
The sample code uses constants to make the exit conditions easier to understand.
# Copyright© 2004 Michael McLean
#
# Usage: perl.exe read_cmdline.pl --infile=<ini_text_file>
# --infile Text file INI settings.
#
# Last Updated [08 Nov 2004]
use strict;
use constant SUCCESS => 1 ;
use constant ERROR => -1 ;
use constant INVALID_SYNTAX => -2 ;
# Parameter count check.
if( scalar( @ARGV ) != 1 )
{
print "Invalid syntax!\n\n";
print "*** Application syntax:\n";
print " read_cmdline.pl --infile=<ini_text_file>\n";
exit( INVALID_SYNTAX );
}
my $infile = $ARGV[0];
# Remove --infile= from command-line parameter.
# Leaves only file name.
if( $infile =~ /^--infile\=(.*)/i )
{
$infile = $1;
$infile =~ s/^\s+//;
}
else
{
print "Invalid syntax!\n\n";
print "*** Application syntax:\n";
print " read_cmdline.pl --infile=<ini_text_file>\n";
exit( INVALID_SYNTAX );
}
# Check length of file name.
# File name MUST be > 2 and < 256 characters in length.
if( length( $infile ) > 255 || length( $infile ) < 3 )
{
print "Invalid --infile value!\n\n";
print "File name length MUST be > 3 && < 255\n";
print " Length = " . length( $infile );
exit( INVALID_SYNTAX );
}
# SUCCESS! Print file name.
print $infile;
