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 <>.

ADVERTISEMENTS

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsPerl
Time10 minute

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 : $total\n";
 
# Use loop to print all args stored in an array called @ARGV
foreach my $a(@ARGV) {
	print "Arg # $counter : $a\n";
	$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 number2\neg: mycal 5 + 3 OR mycal 5 - 2\n";
	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 +, -, *, / only\n";
	exit;
}
print "$ans\n";

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

Fig.01: mycal.pl in action

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
18 comments… add one
  • kunal Nov 23, 2007 @ 13:58

    Hi,
    i think u wrongly misspelled the spelling of line to ling in “Perl display and pass command ling arguments with @argv”

  • jaspreet Sep 6, 2008 @ 6:51

    Helpful info! Thanks!!

  • Chazz Dec 10, 2008 @ 19:22

    Here’s a simple way to display your command args:

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

    or you can use:

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

    Also, if you want to have command line options such as (-a foo), you can use the getopts perl module. Here’s an example:

    use Getopt::Std;
      getopts ("ab:");
      print "a exists\n" if $opt_a;
      print "b = $opt_b\n" if $opt_b;

    The getopts(…) line specifies the options you want. If a letter ends with “:”, then it can provide a string. otherwise it will be a flag option. If the option exists at command line by user, you will have a variable automatically generated prefixed with $opt_. Here’s an example of the command line for the previous code:

    example.pl -a -b foo

    Would display:

    a exists
    b = foo

    The options must be single letter. For longer, more complex command options, see the Getopt::Long perl module (google is your friend).

    Hope this helps.

  • Brian Feb 16, 2009 @ 17:58

    Thanks for proving the information and example for passing command line arguments with $argv. The following line of the calculator script does not work on my system, and I suspect it is related to the “*” metacharacter.

    elsif ( $op eq “*”){
    $ans = $n1 * $n2;

    Being new to Perl scripting, I have to ask if the syntax is correct for this character match? When I execute the script with a multiplication operator, the script returns an error; however, if I change the code to match “x” instead of “*” it runs perfectly.

    Sincerely,
    Brian

  • av May 14, 2009 @ 11:23

    Is there a limit to the num,ber of arguments a perl script can take?

  • rt Aug 12, 2009 @ 13:07

    The first suggestion

    print “$ARGV[$0]\n”;
    print “$ARGV[$1]\n”;
    print “$ARGV[$2]\n”;

    throws an error (undeclared variable) – it uses a zero (0) for each line.

    The followring works –

    print “$ARGV[0]\n”;
    print “$ARGV[1]\n”;
    print “$ARGV[2]\n”;

  • mac Nov 3, 2009 @ 1:19

    Hi Brian,

    Your shell ( dos ) is substituting your * argument. you should either escape it with \* when calling the program or use something else, as you did. quotes would work too:
    calc.pl 10 ‘*’ 15

    Regards,

  • Yogesh Jun 20, 2010 @ 4:39

    Hi, I have a query

    Say for example I have the following in an excel sheet:

    A 1 2 3
    B 4 5 6
    C 7 8 9

    I want to get the data attached to A and say pick up 2 from there and pass it to another perl script irrespective of the cell number in which it is.

    Can u please advise me on that.
    Yogesh

  • Virag Feb 11, 2011 @ 22:41

    Hi
    I have a problem with this
    when i do
    path.pl bus[0] bus[1]

    It is unable to take the arguements with the [] braces and the code terminates

  • Vishal May 11, 2011 @ 4:14

    What is the functionlity of ‘$@’ command line argument in Perl?

  • dileep Oct 20, 2011 @ 14:44

    how to pass linux commands in perl script?

  • M5J5 Jan 6, 2012 @ 19:34

    A couple of corrections if I may:

    1)
    print “$ARGV[$0]\n”;
    print “$ARGV[$1]\n”;
    print “$ARGV[$2]\n”;

    should be read

    print “$ARGV[0]\n”;
    print “$ARGV[1]\n”;
    print “$ARGV[2]\n”;

    2)
    Command Lin*E* not Ling

    THANKS for this post!!!

  • David Apr 9, 2012 @ 17:29

    $#ARGV actually gives you the last index in the @ARGV array, not the total number of arguments passed. scalar(@ARGV) will give you the total number of arguments or just assign to a scalar.
    see http://perldoc.perl.org/perldata.html#Scalar-values for details

    for e.g.

    [root@here]# cat argv.pl
    my $argc = @ARGV;
    my $lastIndex = $#ARGV;
    print "argc=$argc lastIndex=$lastIndex\n";
    
    [root@here]# ./argv.pl
    argc=0 lastIndex=-1
    
    [root@here]# ./argv.pl arg1
    argc=1 lastIndex=0
    
    [root@here]# ./argv.pl arg1 arg2
    argc=2 lastIndex=1
    
  • Patrick Oct 26, 2012 @ 18:55

    Yes, David is correct. $#ARGV is absolutely the WRONG way to get the number of arguments (that’s Bash Script Syntax; not Perl syntax). This post is misleading and should be fixed.

  • Nearco Feb 5, 2016 @ 19:54

    Hi,
    Great example, any tip howto pass the parameters from an external file?.

  • JAGESH Dec 7, 2016 @ 10:23

    HOW TO MERGE two file by command line argument in perl

  • Rahman Adam Feb 4, 2017 @ 5:59

    Hi….
    Can we give the file name path to the Argv command?

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.