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 script.pl "args" "args" command runs the script.pl 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 hello.pl file

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

Execute the script file with the below command

hello.pl one two three

Output:

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

    s

  • 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 - hello.pl

use strict;
use warnings;

use Getopt::Long;

GetOptions(
    "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

hello.pl --filename=abc.txt --config=enable

Output:

abc.txt
enable

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