Background:
From the earliest versions of Perl, the variable @ARGV provided a list of command-line arguments. However, manual parsing easily led to errors. To improve readability and flexibility, the module Getopt::Std was introduced, followed by Getopt::Long and external CPAN modules (e.g., MooX::Options, Getopt::Euclid).
Problem:
"Manual" parsing often does not account for negative numbers, mandatory and multiple flags, parameters with spaces. Different syntax formats (--flag=value, -abc, mixed positions) can make the script unfriendly and easily break if the argument order changes.
Solution:
Use Getopt::Long for advanced parsing of options and flags. It supports long/short options, automatic discovery of variants, arrays, hashes, and various flag formats. For very complex CLI interfaces, CPAN modules with declarative parameter descriptions (MooX::Options, MooseX::Getopt) are used.
Example code:
use Getopt::Long; my $verbose = 0; my $count = 0; my @files; GetOptions( "verbose" => \$verbose, "count=i" => \$count, "file=s" => \@files, ); print "Verbose is $verbose Count is $count Files: @files ";
Key features:
How to distinguish between positional arguments and optional ones when using only Getopt::Std?
Getopt::Std cannot handle long named options or automatically separate positional arguments. After parsing short flags, positional ones are available in @ARGV, but supporting complex syntax requires manual work.
What is the main difference between Getopt::Long and Getopt::Std?
Getopt::Std works only with short (single-character) options, while Getopt::Long can parse long flags, value types, arrays/hashes, and supports non-alphanumeric keys.
Can parameters be accepted through STDIN instead of only through @ARGV?
Yes, but this is not standard for Getopt::Long. For mixed CLI and STDIN inputs, you will need to manually read STDIN and integrate that input into your parsing logic.
The script manually parses each argument from @ARGV in a loop, neglecting values after --arg, handling of --, and incorrectly processing negative numbers (e.g., -5 becomes a flag).
Pros:
Cons:
Using Getopt::Long with a brief description of all variables at the beginning of the file. Supports arrays, mandatory requirements, format checking, and help output.
Pros:
Cons: