basics beginner

How to read command line arguments in Perl

Question

What are the different ways to process command line arguments in Perl?

Perl provides multiple ways to handle command line arguments, from simple to sophisticated:

use strict;
use warnings;

# Method 1: Using @ARGV directly (simple)
my $file = $ARGV[0] or die "Usage: $0 \n";
print "Processing: $file\n";

# Method 2: Using shift
my $input = shift @ARGV || 'default.txt';
my $output = shift @ARGV || 'output.txt';

# Method 3: Using Getopt::Long (recommended)
use Getopt::Long;

my $verbose = 0;
my $config = 'default.conf';
my @include;

GetOptions(
    'verbose|v+'  => \$verbose,
    'config|c=s'  => \$config,
    'include|I=s' => \@include,
) or die "Error in command line arguments\n";

print "Verbose level: $verbose\n";
print "Config: $config\n";
print "Includes: @include\n";

# Usage examples:
# perl script.pl -v -c myconfig.conf
# perl script.pl --verbose --include lib --include modules

Use Getopt::Long for any script that needs options. It handles both short (-v) and long (--verbose) options.

Was this helpful?

Related Questions