How to pass command line arguments to Perl script with an example

This tutorial explains how to pass command line arguments to a perl script file with code examples.

Command line arguments are the way to pass parameters to the perl execution script file.

For example, the "args" "args" command runs the file and pass two arguments to the perl program.

Perl Command Line Arguments Example

First, way using the special variable @ARGV.

Perl provides an inbuilt special variable @ARGV that stores command line arguments as an array.

you can access the arguments using one of the following approaches

  • iterate an array using foreach.
  • access the array using @ARGV[index] index syntax.

Here is an example in file

foreach my $parameter (@ARGV) {
    print $parameter, "\n";

Execute the script file with the below command one two three



The second way, using the Getopt::Long module for command line argument processing Getopt::Long🔗 is a powerful library for managing and processing command line arguments.

  • import Getopt::Long into code to use function


  • Define the format of the predefined command line arguments with GetOptions.

  • You can also define the type and the default value for arguments.

here is an example -

use strict;
use warnings;

use Getopt::Long;

    "filename=s"    => \( my $filename ),                  # string
    "conig=s"   => \( my $config = "disable" ),    # string with default
) or die "command line arguments error";

print( $filename,"\n")
print( $config,"\n")

To run the above program, please issue a command --filename=abc.txt --config=enable



command line arguments are prefixed with -- argument names must be in lowercase only.