How do I read command-line arguments with Perl?

Summary: A quick tip on how to read Perl command line arguments.

When you're writing a Perl script, 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.

A Perl command line arguments example

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

#  PROGRAM:  #

$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

./ 1 2 3 4

or, from a DOS command-line like this

perl 1 2 3 4

you'll get this result:

thanks, you gave me 4 command-line arguments.

Perl command line arguments - Summary

I hope this tip on how to read Perl command line arguments has been helpful. As you can see, the key is knowing about the @ARGV array, and then knowing how to work with Perl arrays in general.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.