Command Line Flags in Perl

Here’s the translation of the Go code example to Perl, with explanations in Markdown format suitable for Hugo:

Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.

Perl provides the Getopt::Long module for parsing command-line options. We’ll use this module to implement our example command-line program.

#!/usr/bin/env perl

use strict;
use warnings;
use Getopt::Long;
use Data::Dumper;

# Declare variables to store our flag values
my $word = 'foo';  # Default value
my $numb = 42;     # Default value
my $fork = 0;      # Default value (false)
my $svar = 'bar';  # Default value

# Parse command-line options
GetOptions(
    "word=s" => \$word,    # String option
    "numb=i" => \$numb,    # Integer option
    "fork"   => \$fork,    # Boolean option
    "svar=s" => \$svar,    # String option
);

# Print out the parsed options and any remaining arguments
print "word: $word\n";
print "numb: $numb\n";
print "fork: ", $fork ? "true" : "false", "\n";
print "svar: $svar\n";
print "tail: ", Dumper(\@ARGV), "\n";

To experiment with the command-line flags program, save it to a file (e.g., command_line_flags.pl) and make it executable:

$ chmod +x command_line_flags.pl

Try out the program by giving it values for all flags:

$ ./command_line_flags.pl --word=opt --numb=7 --fork --svar=flag
word: opt
numb: 7
fork: true
svar: flag
tail: $VAR1 = [];

Note that if you omit flags, they automatically take their default values:

$ ./command_line_flags.pl --word=opt
word: opt
numb: 42
fork: false
svar: bar
tail: $VAR1 = [];

Trailing positional arguments can be provided after any flags:

$ ./command_line_flags.pl --word=opt a1 a2 a3
word: opt
numb: 42
fork: false
svar: bar
tail: $VAR1 = [
          'a1',
          'a2',
          'a3'
        ];

Unlike the flag package in Go, Getopt::Long in Perl allows flags to appear after positional arguments:

$ ./command_line_flags.pl a1 a2 a3 --numb=7
word: foo
numb: 7
fork: false
svar: bar
tail: $VAR1 = [
          'a1',
          'a2',
          'a3'
        ];

You can use the --help flag to get automatically generated help text for the command-line program:

$ ./command_line_flags.pl --help
Usage:
      --word=s     a string (default: "foo")
      --numb=i     an integer (default: 42)
      --fork       a boolean flag
      --svar=s     a string variable (default: "bar")

If you provide a flag that wasn’t specified to the Getopt::Long module, the program will print an error message:

$ ./command_line_flags.pl --wat
Unknown option: wat

This example demonstrates how to use Getopt::Long in Perl to parse command-line options, which is analogous to using the flag package in Go. The concepts are similar, but the implementation details differ to match Perl’s idioms and conventions.