CLI::Cmdline

A minimal, zero-dependency command-line parser in pure Perl – supporting both short and long options.

Perl CPAN version License

Features

All this in ~120 lines of pure Perl. No dependencies.

Installation

perl Makefile.PL
make
make test
make install

Usage

#!/usr/bin/perl
use strict;
use warnings;
use CLI::Cmdline qw(parse);

my $switches = '-v|verbose -x -h|help --quiet';
my $options  = '-f|file --output --header';

my %opt = (
    header  => [],          # collect multiple values
    output  => 'default.out',
    x => 5,
);

CLI::Cmdline::parse(\%opt, $switches, $options)
    or die "Invalid option or missing argument: @ARGV\n";

# @ARGV now contains only positional arguments
print "Verbose level: $opt{v}\n";
print "Output file: $opt{output}\n";
print "Headers: @{$opt{header}}\n" if @{ $opt{header} };

Cmdline examples

$ script.pl -vh --output=out.txt data.txt
# → v=1, h=1, output='out.txt', @ARGV = ('data.txt')

$ script.pl --verbose --verbose --header=title.txt
# → verbose=2, header => ['title.txt']

$ script.pl -f file1.txt -f=file2.txt
# → file => 'file2.txt' (scalar) or ['file1.txt','file2.txt'] if pre-set as []

$ script.pl --unknown
# → dies with error, @ARGV fully restored

$ script.pl --header title.txt -- --
# → header => ['title.txt'], everything after -- left in @ARGV

Perl examples

API

CLI::Cmdline::parse(\%hash, $switches_string, $options_string)

Returns 1 on success, 0 on error.

Development & Testing

The distribution includes a comprehensive test suite:

t/01-basic.t        # 162 tests covering basic features
t/02-alias.t        #  27 tests covering aliases
t/03-complex.t      #  28 tests covering edge cases
t/04-error.t        #  27 tests covering errors
t/05-integration.t  #  24 tests covering script cases

Run with:

prove -v t/*.t

License

This module is free software. You can redistribute it and/or modify it under the same terms as Perl itself.

See the official Perl licensing terms: https://dev.perl.org/licenses/