Command Line Arguments in Perl

In Perl, command-line arguments are accessible through the built-in @ARGV array. Here’s how we can work with command-line arguments:

#!/usr/bin/perl
use strict;
use warnings;

# $0 provides the name of the script
my $argsWithProg = [$0, @ARGV];
my $argsWithoutProg = \@ARGV;

# You can get individual args with normal indexing
my $arg = $ARGV[2];

print "Args with program: @$argsWithProg\n";
print "Args without program: @$argsWithoutProg\n";
print "Third argument: $arg\n";

The @ARGV array in Perl is similar to os.Args in other languages. It contains the command-line arguments passed to the script. However, unlike some other languages, $0 (the name of the script) is not included in @ARGV.

To experiment with command-line arguments, save this script to a file (e.g., command_line_arguments.pl) and run it from the command line:

$ perl command_line_arguments.pl a b c d
Args with program: command_line_arguments.pl a b c d
Args without program: a b c d
Third argument: c

Note that Perl scripts don’t need to be compiled before running. You can execute them directly with the perl interpreter.

In Perl, you can also use modules like Getopt::Long for more advanced command-line argument parsing, which is similar to using flags in other languages.

Next, we’ll look at more advanced command-line processing with option parsing.