Skip to content

Instantly share code, notes, and snippets.

@codescv
Created November 5, 2013 09:13
Show Gist options
  • Save codescv/7316128 to your computer and use it in GitHub Desktop.
Save codescv/7316128 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl -w
# GistID: 7316128
# example: argparse.pl arg1 arg2 arg3 --long-param x -l hh -a arg4 arg5
# params = {"long"=>"x", "short"=>"hh", "switch-a":1}
# args = ("arg1", "arg2", "arg3", "arg4", "arg5")
use strict;
use 5.010;
my %switches = (
"long-param" => ["param", "long"],
"s" => ["param", "short"],
"a" => ["switch", "switch-a"],
);
my %params;
my @args;
while (my $arg = shift) {
my $matched = 0;
for my $key (keys %switches) {
my ($type, $target) = @{$switches{$key}};
if ($arg =~ /--$key=(.*)/) {
$params{$target} = $1;
$matched = 1;
} elsif ($arg eq "--$key") {
$params{$target} = 1;
$matched = 1;
} elsif ($arg eq "-$key") {
if ($type eq "param") {
$params{$target} = shift;
$matched = 1;
} elsif ($type eq "switch") {
$params{$target} = 1;
$matched = 1;
}
}
}
if (!$matched) {
push @args, $arg;
}
}
use Data::Dumper;
say "params: ", Dumper(\%params);
say "args: @args";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment