Learn Perl: Perl Q&A: Reading command-line arguments
Developer's Daily Perl Q&A Center
  main | java | perl | unix | dev directory | web log
   
Main
Perl
Education
Perl Q&A


Question: How do I read command-line arguments with Perl?

Answer:

With Perl, command-line arguments are stored in the array named @ARGV.

$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.

$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.

Here's a simple program that prints the number of command-line arguments it's given, and the values of the arguments:


#!/usr/bin/perl
#---------------------#
#  PROGRAM:  argv.pl  #
#---------------------#

$numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";

foreach $argnum (0 .. $#ARGV) {

   print "$ARGV[$argnum]\n";

}

If you run this program from a Unix command-line like this

./argv.pl 1 2 3 4

or, from a DOS command-line like this

perl argv.pl 1 2 3 4

you'll get this result:
thanks, you gave me 4 command-line arguments.
1
2
3
4

If you're interested in this sample code, click here to download argv.pl.

 

Copyright © 1998 DevDaily Interactive, Inc.
All Rights Reserved.