Perl Display And Pass Command Line Arguments With @argv

How do I read or display command-line arguments with Perl?

Perl command line arguments stored in the special array called @ARGV. The array @ARGV contains the command-line arguments intended for the script. $#ARGV is generally the number of arguments minus one, because $ARGV[0] is the first argument, not the program’s command name itself. Please note that $ARGV contains the name of the current file when reading from <>.

Perl @ARGV examples

Use $ARGV[n] to display argument.

Use $#ARGV to get total number of passed argument to a perl script.

For example, if your scriptname is foo.pl:

./foo.pl one two three

You can print one, two, three command line arguments with print command:

print "$ARGV[0]n";
print "$ARGV[1]n";
print "$ARGV[2]n";

Or just use a loop to display all command line args:

#!/usr/bin/perl
# get total arg passed to this script
my $total = $#ARGV + 1;
my $counter = 1;
 
# get script name
my $scriptname = $0;
 
print "Total args passed to $scriptname : $totaln";
 
# Use loop to print all args stored in an array called @ARGV
foreach my $a(@ARGV) {
	print "Arg # $counter : $an";
	$counter++;
}

Sample outputs:

./script.pl -c tom -m jerry 
Total args passed to /script.pl : 4
Arg # 1 : -c
Arg # 2 : tom
Arg # 3 : -m
Arg # 4 : jerry

More examples

#!/usr/bin/perl -w
if ($#ARGV != 2 ) {
	print "usage: mycal number1 op number2neg: mycal 5 + 3 OR mycal 5 - 2n";
	exit;
}
$n1=$ARGV[0];
$op=$ARGV[1];
$n2=$ARGV[2];
$ans=0;
if ( $op eq "+" ) {
	$ans = $n1 + $n2;
}
elsif ( $op eq "-"){
	$ans = $n1 - $n2;
}
elsif ( $op eq "/"){
	$ans = $n1 / $n2;
}
elsif ( $op eq "*"){
	$ans = $n1 * $n2;
}
else {
	print "Error: op must be +, -, *, / onlyn";
	exit;
}
print "$ansn";

Save and run script as follows:
$ chmod +x mycal.pl
$ ./mycal.pl
$ ./mycal.pl 5 + 3
#### Note: * need to be escaped under UNIX shell ###
$ ./mycal.pl 5 * 3

Sample outputs:

Fig.01: mycal.pl in action

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.