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

Perl Command line arguments code 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



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 functions.
  • 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;

    "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



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

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.