How to read command-line arguments with Perl

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.

Example program

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";

}

Running the sample program

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

What's Related

Very helpful - thanks!

Very helpful - thanks!

alternatives

You can also use this:

$numArgs = @ARGV; #counts the number of elements in @ARGV in scalar context  

instead of:

$numArgs = $#ARGV + 1;

You can use Perl map

Also you can use the Perl map operator:

map { print "$_\n" } @ARGV;

instead of:

foreach $argnum (0 .. $#ARGV) {
  print "$ARGV[$argnum]\n"; 
}

Thanks for the Perl map

Thanks for the Perl map reminder. For some reason I can never remember to use it, and it's much easier than the for loop I have shown.

for(@ARGV){ print

for(@ARGV){
print "$_\n";
}

...is also quite easy ;-)

Great ! Thanks

Thanks !

Post new comment

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